From 5a572b25a037f4f7f4a775ee441aedffb04670d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 27 Sep 2016 23:11:21 +0200 Subject: [PATCH] Refactor the query interface types to enhance extensibility --- CHANGELOG.md | 16 + Documentation/ExtendingGRDB.md | 615 ++++++++++++++ GRDB.xcodeproj/project.pbxproj | 298 +++++-- GRDB/Core/Configuration.swift | 7 + GRDB/Core/Database.swift | 178 +++- GRDB/Core/DatabaseValue.swift | 12 + GRDB/Core/DatabaseValueConvertible.swift | 55 +- GRDB/Core/Statement.swift | 38 +- GRDB/Core/Support/Foundation/NSData.swift | 6 +- GRDB/Core/Support/Foundation/NSDate.swift | 6 +- GRDB/Core/Support/Foundation/NSNull.swift | 2 +- GRDB/Core/Support/Foundation/NSNumber.swift | 2 +- GRDB/Core/Support/Foundation/NSString.swift | 2 +- GRDB/Core/Support/Foundation/NSURL.swift | 2 +- GRDB/Core/Support/Foundation/NSUUID.swift | 2 +- GRDB/Core/Utils.swift | 5 + .../QueryInterfaceRequest.swift | 76 +- .../QueryInterfaceSelectQueryDefinition.swift | 228 +++++ .../SQLCollatedExpression.swift | 49 ++ GRDB/QueryInterface/SQLCollation.swift | 247 ------ GRDB/QueryInterface/SQLCollection.swift | 85 ++ GRDB/QueryInterface/SQLExpression.swift | 733 ++++++++++++++++ GRDB/QueryInterface/SQLFunction.swift | 179 ---- GRDB/QueryInterface/SQLOperator.swift | 470 ---------- GRDB/QueryInterface/SQLOrderingTerm.swift | 90 ++ GRDB/QueryInterface/SQLSelectQuery.swift | 801 ++---------------- GRDB/QueryInterface/SQLSelectable.swift | 114 +++ .../SQLSpecificExpressible.swift | 92 ++ .../QueryInterface/Support/SQLFunctions.swift | 212 +++++ .../QueryInterface/Support/SQLOperators.swift | 785 +++++++++++++++++ ...bleBuilder.swift => TableDefinition.swift} | 113 +-- GRDB/Record/Persistable.swift | 16 +- .../MyPlayground.playground/Contents.swift | 12 +- README.md | 10 +- Support/GRDB-0-84-0-ConversionHelper.swift | 29 + Support/GRDB-Swift2-ConversionHelper.swift | 16 +- ...atabaseValueConvertibleEscapingTests.swift | 26 +- Tests/Private/SQLExpressionLiteralTests.swift | 12 +- .../Core/Database/TextEncodingTests.swift | 61 ++ .../SQLSupportTests.swift | 26 +- .../SQLTableBuilderTests.swift | 2 +- 41 files changed, 3765 insertions(+), 1965 deletions(-) create mode 100644 Documentation/ExtendingGRDB.md create mode 100644 GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift create mode 100644 GRDB/QueryInterface/SQLCollatedExpression.swift delete mode 100644 GRDB/QueryInterface/SQLCollation.swift create mode 100644 GRDB/QueryInterface/SQLCollection.swift create mode 100644 GRDB/QueryInterface/SQLExpression.swift delete mode 100644 GRDB/QueryInterface/SQLFunction.swift delete mode 100644 GRDB/QueryInterface/SQLOperator.swift create mode 100644 GRDB/QueryInterface/SQLOrderingTerm.swift create mode 100644 GRDB/QueryInterface/SQLSelectable.swift create mode 100644 GRDB/QueryInterface/SQLSpecificExpressible.swift create mode 100644 GRDB/QueryInterface/Support/SQLFunctions.swift create mode 100644 GRDB/QueryInterface/Support/SQLOperators.swift rename GRDB/QueryInterface/{SQLTableBuilder.swift => TableDefinition.swift} (88%) create mode 100644 Support/GRDB-0-84-0-ConversionHelper.swift create mode 100644 Tests/Public/Core/Database/TextEncodingTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 430321b5b..367832999 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,12 +5,28 @@ Release Notes **New** +- **Enhanced extensibility**. The low-level types that fuel the query interface [requests](https://github.com/groue/GRDB.swift/#requests) and [expressions][requests](https://github.com/groue/GRDB.swift/#expressions) have been refactored, have lost their underscore prefix, and are stabilizing. A new [GRDB Extension Guide](Documentation/ExtendingGRDB.md) covers common use cases for extending GRDB. + - `TableMapping` protocol learned how to delete all records right from the adopting type: ```swift try Person.deleteAll(db) ``` +- Support for the `LIKE` operator (fixes [#133](https://github.com/groue/GRDB.swift/issues/133)): + + ```swift + // SELECT * FROM persons WHERE email LIKE '%@example.com' + Person.filter(Column("email").like("%@example.com")).fetchAll(db) + ``` + +- `Configuration.textEncoding` let you specify the [text encoding](https://www.sqlite.org/pragma.html#pragma_encoding) of a database. + +**Breaking Changes** + +- The SQLForeignKeyAction, SQLColumnType, SQLConflictResolution, and SQLCollation types have been renamed Database.ForeignKeyAction, Database.ColumnType, Database.ConflictResolution, and Database.CollationName. + + ## 0.84.0 Released September 16, 2016 diff --git a/Documentation/ExtendingGRDB.md b/Documentation/ExtendingGRDB.md new file mode 100644 index 000000000..4708febf4 --- /dev/null +++ b/Documentation/ExtendingGRDB.md @@ -0,0 +1,615 @@ +GRDB Extension Guide +==================== + +**Some parts of GRDB are extensible, so that you can make it better fit your needs.** + +This guide is a step-by-step tour of GRDB extensibility, around a few topics: + +- **[Add a value type](#add-a-value-type)** + + You'll learn how to turn UIColor into a value type that you can store, fetch, and use in your records: + + ```swift + for row in Row.fetch(db, "SELECT name, color FROM clothes") { + let name: String = row.value(named: "name") + let color: UIColor = row.value(named: "color") // <-- New! UIColor as value + } + ``` + +- **[Add an SQLite function or operator](#add-an-sqlite-function-or-operator)** + + You'll learn how to add support for the [STRFTIME](https://www.sqlite.org/lang_datefunc.html) and [ROUND](https://www.sqlite.org/lang_corefunc.html#round) functions, and the [MATCH](https://www.sqlite.org/fts3.html#full_text_index_queries) full-text operator: + + ```swift + Books.select(strftime("%Y", Column("publishedDate"))) // <-- New! strftime function + Player.select(Column("score").rounded(decimals: -1)) // <-- New! rounded method + Books.filter("\"Moby Dick\"" ~= Column("body")) // <-- New! ~= operator + ``` + +- **[Add a new kind of SQLite expression](#add-a-new-kind-of-sqlite-expression)** + + You'll learn how to add support for [CAST expressions](https://www.sqlite.org/lang_expr.html#castexpr): + + ```swift + let jsonString = Column("jsonString") + let request = Books.select(cast(jsonString, as: .blob)) // <-- New! cast function + for row in Row.fetch(db, request) { + let data = row.dataNoCopy(atIndex: 0) + } + ``` + +- **Extend the query interface requests** + + You may need to extend the [query interface requests](../README.md#request) so that their SELECT queries could embed recursive clauses, table joins, etc. + + Pull requests are welcome. Open issues if you have questions. + + +- **Support a new kind of SQL query** + + For example, you may need to generate SQL triggers, or create specific kinds of virtual tables. + + Pull requests are welcome. Open issues if you have questions. + + +## Add a Value Type + +**All value types adopt the [DatabaseValueConvertible protocol](../README.md#custom-value-types).** + +```swift +protocol DatabaseValueConvertible { + /// Returns a value that can be stored in the database. + var databaseValue: DatabaseValue { get } + + /// Returns a value initialized from databaseValue, if possible. + static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? +} +``` + +The `databaseValue` property returns [DatabaseValue](../README.md#databasevalue), a type that wraps the five values supported by SQLite: NULL, Int64, Double, String and Data. DatabaseValue has no public initializer: to create one, use `DatabaseValue.null`, or another type that already adopts the protocol: `1.databaseValue`, `"foo".databaseValue`, etc. + +The `fromDatabaseValue()` factory method returns an instance of your custom type if the databaseValue contains a suitable value. If the databaseValue does not contain a suitable value, such as "foo" for Date, the method returns nil. + +**What does the DatabaseValueConvertible protocol bring to a type like UIColor?** + +Well, you will be able to use UIColor like all other [value types](../README.md#values) (Bool, Int, String, Date, Swift enums, etc.): + +- Use UIColor as [statement arguments](../README.md#executing-updates): + + ```swift + try db.execute( + "INSERT INTO clothes (name, color) VALUES (?, ?)", + arguments: ["Shirt", UIColor.red]) + ``` + +- UIColor can be [extracted from rows](../README.md#column-values): + + ```swift + for row in Row.fetch(db, "SELECT * FROM clothes") { + let name: String = row.value(named: "name") + let color: UIColor = row.value(named: "color") + } + ``` + +- UIColor can be [directly fetched](../README.md#value-queries): + + ```swift + let colors = UIColor.fetchAll(db, "SELECT DISTINCT color FROM clothes") // [UIColor] + ``` + +- Use UIColor in [Records](../README.md#records): + + ```swift + class ClothingItem : Record { + var name: String + var color: UIColor + + required init(row: Row) { + name = row.value(named: "name") + color = row.value(named: "color") + super.init(row: row) + } + + override var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["name": name, "color": color] + } + } + ``` + +- Use UIColor in the [query interface](../README.md#the-query-interface): + + ```swift + let redClothes = ClothingItem.filter(colorColumn == UIColor.red).fetchAll(db) + ``` + +**Let's have UIColor adopt DatabaseValueConvertible** + +In order to preserve as most information as possible, we'll archive UIColor as a data blob using the NSCoding protocol. But YMMV. + +```swift +extension UIColor : DatabaseValueConvertible { + + /// Encode UIColor as a data blob + var databaseValue: DatabaseValue { + // Use NSKeyedArchiver to build Data + let data = NSKeyedArchiver.archivedData(withRootObject: self) + + // Data is already DatabaseValueConvertible + return data.databaseValue + } + + /// Returns a UIColor if databaseValue contains suitable data, and + /// nil otherwise. + static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? { + // Only Data blobs can contain a UIColor + guard let data = Data.fromDatabaseValue(databaseValue) else { + return nil + } + + // We're looking for an archived object + guard let color = NSKeyedUnarchiver.unarchiveObject(with: data) else { + return nil + } + + // The cast function will return nil if the unarchived object doesn't + // have the correct type + return cast(color) // Converts Any to Self? + } +} +``` + +Use the `cast` utility function when you want *non-final classes* to implement DatabaseValueConvertible. It avoids compiler errors that are not easy to deal with. Note that final classes and value types won't need it. + +```swift +// Workaround Swift inconvenience around factories methods of non-final classes +func cast(_ value: T) -> U? { + return value as? U +} +``` + + +## Add an SQLite Function or Operator + +**When an SQLite [function](https://www.sqlite.org/lang_corefunc.html) or [operator](https://www.sqlite.org/lang_expr.html) is missing from GRDB**, this usually means that there hasn't been a [feature request](http://github.com/groue/GRDB.swift/issues) yet. + +But you don't have to wait: you can extend GRDB and the query interface to add support for the missing syntax element (and eventually submit a pull request later). + +Let's remind our goal: we'll add the [STRFTIME](https://www.sqlite.org/lang_datefunc.html) and [ROUND](https://www.sqlite.org/lang_corefunc.html#round) functions, and the [MATCH](https://www.sqlite.org/fts3.html#full_text_index_queries) full-text operator. + +Their SQL usage is the following: + +```sql +-- Publication years of books +SELECT STRFTIME('%Y', publishedOn) FROM books; +-- Players' scores, rounded to the nearest ten +SELECT ROUND(score, -1) FROM players; +-- Books that talk about Moby Dick +SELECT * FROM books WHERE body MATCH '"Moby Dick"'; +``` + +Translated in the query interface, this gives: + +```swift +Books.select(strftime("%Y", Column("publishedDate"))) +Player.select(Column("score").rounded(decimals: -1)) +Books.filter("\"Moby Dick\"" ~= Column("body")) +``` + +`strftime` is a top-level Swift function because this is how GRDB usually imports SQLite functions which do not have matching standard Swift counterpart, like AVG, LEGNTH, SUM. It helps the Swift code looking like SQL when it is relevant. + +Conversely, we expose the ROUND SQL function as the `rounded` Swift method. That's because `rounded` is the standard Swift method that rounds floating-point values. + +Last, we expose the MATCH SQL operator as the `~=` Swift operator, just because this is the standard Swift [pattern matching operator](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Patterns.html). + +Whenever you import a SQL feature to Swift, you'll have to decide: should you preserve the SQL look and feel, or adopt a well-established swiftism? It's really up to you. + + +### STRFTIME + +The [STRFTIME](https://www.sqlite.org/lang_datefunc.html) SQL function accepts many arguments. We'll simplify it to `strftime(format, date)`, so that we can write: + +```sql +// Publication years of books +// SELECT STRFTIME('%Y', publishedOn) FROM books +Books.select(strftime("%Y", Column("publishedDate"))) +``` + +The signature of the Swift `strftime` function is: + +```swift +func strftime(_ format: String, _ date: SQLSpecificExpressible) -> SQLExpression +``` + +SQLSpecificExpressible and SQLExpression are types of the [query interface](../README.md#the-query-interface) that you do not usually see. We have moved down one floor, closer to the SQL guts of GRDB. We'll see more new types and protocols below. + +The return value is SQLExpression. All GRDB functions and operators that build [query interface expressions](../README.md#expressions) return values of this type. It represents actual [SQLite expressions](https://www.sqlite.org/lang_expr.html). + +SQLExpression is a protocol, so that you can build your own [custom expressions](#add-a-new-kind-of-sqlite-expression). But GRDB ships with a variety of [built-in expressions](#built-in-expressions) that are ready-made, and here we'll use SQLExpressionFunction that is dedicated to function calls: + +```swift +struct SQLExpressionFunction : SQLExpression { + /// Creates an SQL function call + /// + /// // ABS(-1) + /// SQLExpressionFunction(.abs, arguments: -1) + init(_ functionName: SQLFunctionName, arguments: SQLExpressible...) +} +``` + +So here is the code that defines our `strftime` function: + +```swift +// Add a SQLFunctionName just like we add NSNotification.Name since +// the release of Swift 3. +extension SQLFunctionName { + /// The `STRFTIME` SQL function + static let strftime = SQLFunctionName("STRFTIME") +} + +/// Returns an expression that evaluates the `STRFTIME` SQL function. +/// +/// // STRFTIME('%Y', date) +/// strftime("%Y", Column("date")) +func strftime(_ format: String, _ date: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionFunction(.strftime, arguments: format, date) +} +``` + +The `strftime` function is now complete, ready to be used. We haven't yet described the SQLSpecificExpressible type of the `date` argument: + +SQLSpecificExpressible is the protocol for all types that can be turned into a SQL expression, but types like Int, Date, or UIColor that exist outside of GRDB and the query interface. Having `strftime` accept a SQLSpecificExpressible date prevents it from polluting the global space. It is *specific* to GRDB: + +```swift +strftime("%Y", Date()) // Compiler error +strftime("%Y", Column("date")) // SQLExpression: STRFTIME('%Y', date) +``` + +You may want to compare it to another protocol, SQLExpressible, which will be described [below](#add-a-new-kind-of-sqlite-expression), when we add support for CAST SQL expressions. + +> :point_up: **Note**: whenever you extend GRDB with a Swift function, method, or operator, you should generally make sure that its signature contains at least one GRDB-specific type. In the `strftime` function, it is the SQLSpecificExpressible protocol. + + +### ROUND + +We want to expose the [ROUND](https://www.sqlite.org/lang_corefunc.html#round) SQLite function as a `rounded` Swift method: + +```swift +// Players' scores, rounded to the nearest ten +// SELECT ROUND(score, -1) FROM players +Player.select(Column("score").rounded(decimals: -1)) +``` + +Based on the implementation of the [`strftime`](#strftime) function above, we can write the `rounded` method straight away: + +```swift +extension SQLFunctionName { + /// The `ROUND` SQL function + static let round = SQLFunctionName("ROUND") +} + +extension SQLSpecificExpressible { + func rounded(decimals: Int = 0) -> SQLExpression { + if decimals == 0 { + // ROUND(value) + return SQLExpressionFunction(.round, arguments: self) + } else { + // ROUND(value, decimals) + return SQLExpressionFunction(.round, arguments: self, decimals) + } + } +} +``` + +The `rounded` method is declared in an extension to the SQLSpecificExpressible protocol, because it should be available on all types that can be turned into a SQL expression, without messing with types that exist outside of GRDB such as Float and Double: + +```swift +3.1416.rounded() // 3 +3.1416.rounded(.up) // 4 +3.1416.rounded(decimals: 1) // Compiler error +Column("score").rounded() // SQLExpression: ROUND(score) +``` + +> :point_up: **Note**: whenever you extend GRDB with a Swift function, method, or operator, you should generally make sure that its signature contains at least one GRDB-specific type. In the `rounded` method, it is the extended SQLSpecificExpressible protocol. + + +### MATCH + +For the [MATCH](https://www.sqlite.org/fts3.html#full_text_index_queries) full-text operator, we want to use the ~= Swift operator: + +```swift +// Books that talk about Moby Dick +// SELECT * FROM books WHERE body MATCH '"Moby Dick"' +Books.filter("\"Moby Dick\"" ~= Column("body")) +``` + +This time we can't use the SQLExpressionFunction type, because it can't generate the SQL for a binary operator. Instead, we'll use another [built-in expression](#built-in-expressions), SQLExpressionBinary: + +```swift +struct SQLExpressionBinary : SQLExpression { + /// Creates an expression made of two expressions joined with a binary operator. + /// + /// // length * width + /// SQLExpressionBinary(.multiply, Column("length"), Column("width")) + init(_ op: SQLBinaryOperator, _ lhs: SQLExpressible, _ rhs: SQLExpressible) +} +``` + +Now we have to find the signature of our Swift operator. The MATCH operator requires an indexed column on its left. Anything can go on its right, strings but also any SQL expression. + +The Swift `~=` operator inverts the order of arguments, so this eventually gives the following signature: + +```swift +func ~= (_ lhs: SQLExpressible, _ rhs: Column) -> SQLExpression +``` + +SQLExpressible is the protocol for all types that can be turned into a SQL expression. This includes all expressions, and all [value types](../README.md#values) (including String, for our full-text pattern). + +The final implementation follows: + +```swift +// Add a SQLBinaryOperator just like we add NSNotification.Name since +// the release of Swift 3. +extension SQLBinaryOperator { + /// The `MATCH` binary operator + static let match = SQLBinaryOperator("MATCH") +} + +func ~= (_ lhs: SQLExpressible, _ rhs: Column) -> SQLExpression { + return SQLExpressionBinary(.match, rhs, lhs) +} +``` + +Let's check a few usages of the ~= operator: + +```swift +"pattern" ~= "content" // false (standard Swift ~= operator) +"pattern" ~= Column("content") // SQL expression: content MATCH 'pattern' +Column("pattern") ~= "content" // Compiler error +Column("pattern") ~= Column("content") // SQL expression: content MATCH pattern +``` + +> :point_up: **Note**: whenever you extend GRDB with a Swift function, method, or operator, you should generally make sure that its signature contains at least one GRDB-specific type. In the `~=` operator, it is the Column type. + + +### Built-in Expressions + +When you extend GRDB with a new function, method, or operator that generates an [SQL expression](https://www.sqlite.org/lang_expr.html), you have to return a value the adopts the SQLExpression protocol. + +We have already seen in [our](#strftime) [previous](#round) [examples](#match) two concrete types that generate SQL function calls and binary operators: SQLExpressionFunction and SQLExpressionBinary. + +This section of the documentation lists all built-in expressions. Adding a custom SQLExpression type will be documented [below](#add-a-new-kind-of-sqlite-expression). + + +#### Column and DatabaseValue + +The [Column](../README.md#the-query-interface) type from the query interface, and [DatabaseValue](../README.md#databasevalue), the type that wraps the five values supported by SQLite (NULL, Int64, Double, String and Data) are expressions. They are rather trivial, and it is unlikely that you use them in your GRDB extensions. + + +#### SQLExpressionLiteral + +Use SQLExpressionLiteral when you need to go fast: + +```swift +struct SQLExpressionLiteral : SQLExpression { + /// Creates an SQL literal expression. + /// + /// SQLExpressionLiteral("1 + 2") + /// SQLExpressionLiteral("? + ?", arguments: [1, 2]) + init(_ sql: String, arguments: StatementArguments? = nil) +} +``` + +For an example of use, see the [Add a new kind of SQLite expression](#add-a-new-kind-of-sqlite-expression) chapter. + + +#### SQLExpressionUnary + +SQLExpressionUnary builds an expression by prefixing another expression with an unary operator: + +```swift +struct SQLExpressionUnary : SQLExpression { + /// Creates an expression made of an unary operator and + /// an operand expression. + /// + /// // NOT favorite + /// SQLExpressionUnary(.not, Column("favorite")) + init(_ op: SQLUnaryOperator, _ value: SQLExpressible) +} +``` + +You add missing SQLite unary operators by extending SQLUnaryOperator: + +```swift +extension SQLUnaryOperator { + /// The `+` unary operator + static let plus = SQLUnaryOperator("+", needsRightSpace: false) +} +``` + + +#### SQLExpressionBinary + +SQLExpressionBinary builds an expression by joining two expressions with a binary operator: + +```swift +struct SQLExpressionBinary : SQLExpression { + /// Creates an expression made of two expressions joined with a binary operator. + /// + /// // length * width + /// SQLExpressionBinary(.multiply, Column("length"), Column("width")) + init(_ op: SQLBinaryOperator, _ lhs: SQLExpressible, _ rhs: SQLExpressible) +} +``` + +You add missing SQLite binary operators by extending SQLBinaryOperator: + +```swift +extension SQLBinaryOperator { + /// The `MATCH` binary operator + static let match = SQLBinaryOperator("MATCH") +} +``` + + +#### SQLExpressionFunction + +SQLExpressionFunction builds an SQL function call: + +```swift +struct SQLExpressionFunction : SQLExpression { + /// Creates an SQL function call + /// + /// // ABS(-1) + /// SQLExpressionFunction(.abs, arguments: -1) + init(_ functionName: SQLFunctionName, arguments: SQLExpressible...) +} +``` + +You add missing SQLite function names by extending SQLFunctionName: + +```swift +extension SQLFunctionName { + /// The `STRFTIME` SQL function + static let strftime = SQLFunctionName("STRFTIME") +} +``` + + +#### The IN Operator + +Build a `value IN (...)` expression from any sequence of [values](../README.md#values): + +```swift +// SQLExpression: id IN (1, 2, 3) +[1,2,3].contains(Column("id")) + +// SQLExpression: id NOT IN (1, 2, 3) +![1,2,3].contains(Column("id")) +``` + +The most general way to generate an `IN` operator is from any value that adopts the [SQLCollection](#TODO) protocol, like the [query interface requests](../README.md#request): + +```swift +let request = Person.select(Column("id")) + +// SQLExpression: in IN (SELECT id FROM persons) +request.contains(Column("id")) +``` + + +#### The BETWEEN Operator + +Build a `value BETWEEN min AND max` expression from Swift ranges: + +```swift +// SQLExpression: id BETWEEN 1 AND 10 +1...10.contains(Column("id") +``` + + +#### The EXISTS Operator + +Build a `EXISTS(...)` expression from any value that adopts the [SQLSelectQuery](#TODO) protocol, like the [query interface requests](../README.md#request): + +```swift +let request = Person.all() + +// SQLExpression: EXISTS(SELECT * FROM persons) +request.exists() +``` + + +#### The COUNT Function + +Build a `COUNT(...)` expression from the [count](#TODO) and [count(distinct:)](#TODO) functions: + +```swift +// SQLExpression: COUNT(email) +count(Column("email")) + +// SQLExpression: COUNT(DISTINCT email) +count(distinct: Column("email")) +``` + + +#### The COLLATE Operator + +Build a `expression COLLATE collation` expression with the `collating` method: + +```swift +// SQLExpression: name = 'Arthur' COLLATE NOCASE +Column("name").collating(.nocase) == "Arthur" +``` + + +## Add a New Kind of SQLite Expression + +GRDB does not have built-in support for the full range of the SQLite [expression grammar](https://www.sqlite.org/lang_expr.html). + +For example, [CAST expressions](https://www.sqlite.org/lang_expr.html#castexpr) are not ready-made. They can be useful, though: a CAST expression can efficiently convert json strings to UTF-8 data blobs for you: + +```sql +SELECT CAST(jsonString AS BLOB) FROM books +``` + +We'll add below a Swift `cast` function: + +```swift +let request = Books.select(cast(Column("jsonString"), as: .blob)) +let jsonDatas = Data.fetchAll(db, request) // [Data] +``` + +`cast` is a top-level Swift function because this is how GRDB usually imports SQLite features which do not have matching standard Swift counterpart. It helps the Swift code looking like SQL when it is relevant. But YMMV. + +The signature of the `cast` function is: + +```swift +func cast(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression +``` + +Database.ColumnType is a String-based enumeration of all database column types (.integer, .text, .blob, etc.) You have already used if you have [created tables](../README.md#create-tables) using the query interface. + +The return type SQLExpression is the type returned by all GRDB functions and operators that build [query interface expressions](../README.md#expressions). + +SQLExpression is a protocol. But GRDB ships with a variety of [built-in expressions](#built-in-expressions) that are ready-made, so that you generally don't have to write your custom expression type. Here we need something new. So we'll use the most versatile of all, SQLExpressionLiteral: + +```swift +struct SQLExpressionLiteral : SQLExpression { + /// Creates an SQL literal expression. + /// + /// SQLExpressionLiteral("1 + 2") + /// SQLExpressionLiteral("? + ?", arguments: [1, 2]) + init(_ sql: String, arguments: StatementArguments? = nil) +} +``` + +Here is the code that defines our `cast` function: + + +```swift +func cast(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression { + // Turn the value into a literal expression + let literal: SQLExpressionLiteral = value.sqlExpression.literal + + // Build our "CAST(value AS type)" sql snippet + let sql = "CAST(\(literal.sql) AS \(type.rawValue))" + + // And return a new literal expression, preserving input arguments + return SQLExpressionLiteral(sql, arguments: literal.arguments) +} +``` + +We haven't yet described the SQLExpressible type of the `value` argument: + +SQLExpressible is the protocol for all types that can be turned into a SQL expression. This includes all [value types](../README.md#values) (Bool, Int, String, Date, Swift enums, etc.): + +```swift +cast("foo", as: .blob) // SQLExpression: CAST('foo' AS BLOB) +cast(Column("name"), as: .blob) // SQLExpression: CAST(name AS BLOB) +``` + +You may want to compare it to another protocol, SQLSpecificExpressible, which has been described [above](#strftime), when we were adding support for the STRFTIME SQL function. + +> :point_up: **Note**: whenever you extend GRDB with a Swift function, method, or operator, you should generally make sure that its signature contains at least one GRDB-specific type. In the `cast` function, it is Database.ColumnType. + +**If SQLExpressionLiteral reveals too limited for your purpose**, you may have to implement a new type that adopts the [SQLExpression](#TODO) protocol. diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index d9a9a826a..1b2c89a7d 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -29,14 +29,10 @@ 5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; 5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; 5605F1881C69111300235C62 /* StatementInformationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* StatementInformationTests.swift */; }; - 5605F18D1C6B1A8700235C62 /* SQLCollation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollation.swift */; }; - 5605F18E1C6B1A8700235C62 /* SQLCollation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollation.swift */; }; - 5605F18F1C6B1A8700235C62 /* SQLFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18A1C6B1A8700235C62 /* SQLFunction.swift */; }; - 5605F1901C6B1A8700235C62 /* SQLFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18A1C6B1A8700235C62 /* SQLFunction.swift */; }; - 5605F1911C6B1A8700235C62 /* SQLOperator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18B1C6B1A8700235C62 /* SQLOperator.swift */; }; - 5605F1921C6B1A8700235C62 /* SQLOperator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18B1C6B1A8700235C62 /* SQLOperator.swift */; }; - 5605F1931C6B1A8700235C62 /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */; }; - 5605F1941C6B1A8700235C62 /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */; }; + 5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; + 5605F18E1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; + 5605F1931C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */; }; + 5605F1941C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */; }; 5606AF911C0ED37000D20487 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 56BB86301BA98AB0001F9168 /* libsqlite3.tbd */; }; 5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; }; 560A37A41C8F625000949E71 /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A31C8F625000949E71 /* DatabasePool.swift */; }; @@ -68,11 +64,10 @@ 560D924B1C672C4B00F4F92B /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableMapping.swift */; }; 560D924C1C672C4B00F4F92B /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableMapping.swift */; }; 560FC51C1CB003810014AA8E /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; - 560FC51D1CB003810014AA8E /* SQLCollation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollation.swift */; }; + 560FC51D1CB003810014AA8E /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; 560FC51E1CB003810014AA8E /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563445041C4A7FD7003D3DC6 /* Utils.swift */; }; 560FC51F1CB003810014AA8E /* CGFloat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1491C672E4000235C62 /* CGFloat.swift */; }; 560FC5201CB003810014AA8E /* Date.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F14F1C672E4000235C62 /* Date.swift */; }; - 560FC5211CB003810014AA8E /* SQLFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18A1C6B1A8700235C62 /* SQLFunction.swift */; }; 560FC5221CB003810014AA8E /* RawRepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1571C672E4000235C62 /* RawRepresentable.swift */; }; 560FC5231CB003810014AA8E /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238701B9C75030082EB20 /* Configuration.swift */; }; 560FC5241CB003810014AA8E /* DatabaseWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363C31C942C37000BE133 /* DatabaseWriter.swift */; }; @@ -82,14 +77,13 @@ 560FC5291CB003810014AA8E /* DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */; }; 560FC52A1CB003810014AA8E /* DatabaseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238731B9C75030082EB20 /* DatabaseError.swift */; }; 560FC52B1CB003810014AA8E /* DatabaseValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238751B9C75030082EB20 /* DatabaseValue.swift */; }; - 560FC52C1CB003810014AA8E /* SQLOperator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18B1C6B1A8700235C62 /* SQLOperator.swift */; }; 560FC52E1CB003810014AA8E /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; 560FC52F1CB003810014AA8E /* DatabaseCoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F14B1C672E4000235C62 /* DatabaseCoder.swift */; }; 560FC5301CB003810014AA8E /* NSURL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1531C672E4000235C62 /* NSURL.swift */; }; 560FC5311CB003810014AA8E /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableMapping.swift */; }; 560FC5321CB003810014AA8E /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A31C8F625000949E71 /* DatabasePool.swift */; }; 560FC5331CB003810014AA8E /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; - 560FC5341CB003810014AA8E /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */; }; + 560FC5341CB003810014AA8E /* QueryInterfaceSelectQueryDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */; }; 560FC5351CB003810014AA8E /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238781B9C75030082EB20 /* Statement.swift */; }; 560FC5361CB003810014AA8E /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; 560FC5371CB003810014AA8E /* DatabaseSchemaCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */; }; @@ -264,11 +258,9 @@ 565490D81D5AE252005622CB /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; 565490D91D5AE252005622CB /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; 565490DA1D5AE252005622CB /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; - 565490DB1D5AE252005622CB /* SQLCollation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollation.swift */; }; - 565490DC1D5AE252005622CB /* SQLFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18A1C6B1A8700235C62 /* SQLFunction.swift */; }; - 565490DD1D5AE252005622CB /* SQLOperator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18B1C6B1A8700235C62 /* SQLOperator.swift */; }; - 565490DE1D5AE252005622CB /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */; }; - 565490DF1D5AE252005622CB /* SQLTableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* SQLTableBuilder.swift */; }; + 565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; + 565490DE1D5AE252005622CB /* QueryInterfaceSelectQueryDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */; }; + 565490DF1D5AE252005622CB /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 565490E01D5AE252005622CB /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; 565490E11D5AE252005622CB /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* Persistable.swift */; }; 565490E21D5AE252005622CB /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; @@ -358,12 +350,76 @@ 565F03C31CE5D3AA00DE108F /* AdapterRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* AdapterRowTests.swift */; }; 565F03C41CE5D3AA00DE108F /* AdapterRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* AdapterRowTests.swift */; }; 565F03C71CE5D3AA00DE108F /* AdapterRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* AdapterRowTests.swift */; }; - 566AD8B21D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* SQLTableBuilder.swift */; }; - 566AD8B31D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* SQLTableBuilder.swift */; }; - 566AD8B41D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* SQLTableBuilder.swift */; }; - 566AD8B51D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* SQLTableBuilder.swift */; }; - 566AD8B61D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* SQLTableBuilder.swift */; }; - 566AD8B71D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* SQLTableBuilder.swift */; }; + 5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475991D97D8A000FF74B8 /* SQLCollection.swift */; }; + 5664759B1D97D8A000FF74B8 /* SQLCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475991D97D8A000FF74B8 /* SQLCollection.swift */; }; + 5664759C1D97D8A000FF74B8 /* SQLCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475991D97D8A000FF74B8 /* SQLCollection.swift */; }; + 5664759D1D97D8A000FF74B8 /* SQLCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475991D97D8A000FF74B8 /* SQLCollection.swift */; }; + 5664759E1D97D8A000FF74B8 /* SQLCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475991D97D8A000FF74B8 /* SQLCollection.swift */; }; + 5664759F1D97D8A000FF74B8 /* SQLCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475991D97D8A000FF74B8 /* SQLCollection.swift */; }; + 566475A01D97D8A000FF74B8 /* SQLCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475991D97D8A000FF74B8 /* SQLCollection.swift */; }; + 566475A21D9810A400FF74B8 /* SQLSelectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475A11D9810A400FF74B8 /* SQLSelectable.swift */; }; + 566475A31D9810A400FF74B8 /* SQLSelectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475A11D9810A400FF74B8 /* SQLSelectable.swift */; }; + 566475A41D9810A400FF74B8 /* SQLSelectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475A11D9810A400FF74B8 /* SQLSelectable.swift */; }; + 566475A51D9810A400FF74B8 /* SQLSelectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475A11D9810A400FF74B8 /* SQLSelectable.swift */; }; + 566475A61D9810A400FF74B8 /* SQLSelectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475A11D9810A400FF74B8 /* SQLSelectable.swift */; }; + 566475A71D9810A400FF74B8 /* SQLSelectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475A11D9810A400FF74B8 /* SQLSelectable.swift */; }; + 566475A81D9810A400FF74B8 /* SQLSelectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475A11D9810A400FF74B8 /* SQLSelectable.swift */; }; + 566475AA1D9818B100FF74B8 /* GRDB-0-84-0-ConversionHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475A91D9818B100FF74B8 /* GRDB-0-84-0-ConversionHelper.swift */; }; + 566475AB1D9818B100FF74B8 /* GRDB-0-84-0-ConversionHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475A91D9818B100FF74B8 /* GRDB-0-84-0-ConversionHelper.swift */; }; + 566475AC1D9818B100FF74B8 /* GRDB-0-84-0-ConversionHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475A91D9818B100FF74B8 /* GRDB-0-84-0-ConversionHelper.swift */; }; + 566475AD1D9818B100FF74B8 /* GRDB-0-84-0-ConversionHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475A91D9818B100FF74B8 /* GRDB-0-84-0-ConversionHelper.swift */; }; + 566475AE1D9818B100FF74B8 /* GRDB-0-84-0-ConversionHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475A91D9818B100FF74B8 /* GRDB-0-84-0-ConversionHelper.swift */; }; + 566475AF1D9818B100FF74B8 /* GRDB-0-84-0-ConversionHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475A91D9818B100FF74B8 /* GRDB-0-84-0-ConversionHelper.swift */; }; + 566475B01D9818B100FF74B8 /* GRDB-0-84-0-ConversionHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475A91D9818B100FF74B8 /* GRDB-0-84-0-ConversionHelper.swift */; }; + 566475B21D9819D500FF74B8 /* SQLOrderingTerm.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475B11D9819D500FF74B8 /* SQLOrderingTerm.swift */; }; + 566475B31D9819D500FF74B8 /* SQLOrderingTerm.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475B11D9819D500FF74B8 /* SQLOrderingTerm.swift */; }; + 566475B41D9819D500FF74B8 /* SQLOrderingTerm.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475B11D9819D500FF74B8 /* SQLOrderingTerm.swift */; }; + 566475B51D9819D500FF74B8 /* SQLOrderingTerm.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475B11D9819D500FF74B8 /* SQLOrderingTerm.swift */; }; + 566475B61D9819D500FF74B8 /* SQLOrderingTerm.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475B11D9819D500FF74B8 /* SQLOrderingTerm.swift */; }; + 566475B71D9819D500FF74B8 /* SQLOrderingTerm.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475B11D9819D500FF74B8 /* SQLOrderingTerm.swift */; }; + 566475B81D9819D500FF74B8 /* SQLOrderingTerm.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475B11D9819D500FF74B8 /* SQLOrderingTerm.swift */; }; + 566475BA1D981AD200FF74B8 /* SQLSpecificExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475B91D981AD200FF74B8 /* SQLSpecificExpressible.swift */; }; + 566475BB1D981AD200FF74B8 /* SQLSpecificExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475B91D981AD200FF74B8 /* SQLSpecificExpressible.swift */; }; + 566475BC1D981AD200FF74B8 /* SQLSpecificExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475B91D981AD200FF74B8 /* SQLSpecificExpressible.swift */; }; + 566475BD1D981AD200FF74B8 /* SQLSpecificExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475B91D981AD200FF74B8 /* SQLSpecificExpressible.swift */; }; + 566475BE1D981AD200FF74B8 /* SQLSpecificExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475B91D981AD200FF74B8 /* SQLSpecificExpressible.swift */; }; + 566475BF1D981AD200FF74B8 /* SQLSpecificExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475B91D981AD200FF74B8 /* SQLSpecificExpressible.swift */; }; + 566475C01D981AD200FF74B8 /* SQLSpecificExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475B91D981AD200FF74B8 /* SQLSpecificExpressible.swift */; }; + 566475C21D981C5D00FF74B8 /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475C11D981C5D00FF74B8 /* SQLSelectQuery.swift */; }; + 566475C31D981C5D00FF74B8 /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475C11D981C5D00FF74B8 /* SQLSelectQuery.swift */; }; + 566475C41D981C5D00FF74B8 /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475C11D981C5D00FF74B8 /* SQLSelectQuery.swift */; }; + 566475C51D981C5D00FF74B8 /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475C11D981C5D00FF74B8 /* SQLSelectQuery.swift */; }; + 566475C61D981C5D00FF74B8 /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475C11D981C5D00FF74B8 /* SQLSelectQuery.swift */; }; + 566475C71D981C5D00FF74B8 /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475C11D981C5D00FF74B8 /* SQLSelectQuery.swift */; }; + 566475C81D981C5D00FF74B8 /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475C11D981C5D00FF74B8 /* SQLSelectQuery.swift */; }; + 566475CC1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */; }; + 566475CD1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */; }; + 566475CE1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */; }; + 566475CF1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */; }; + 566475D01D981D5E00FF74B8 /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */; }; + 566475D11D981D5E00FF74B8 /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */; }; + 566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */; }; + 566475D31D981D5E00FF74B8 /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */; }; + 566475D41D981D5E00FF74B8 /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */; }; + 566475D51D981D5E00FF74B8 /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */; }; + 566475D61D981D5E00FF74B8 /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */; }; + 566475D71D981D5E00FF74B8 /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */; }; + 566475D81D981D5E00FF74B8 /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */; }; + 566475D91D981D5E00FF74B8 /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */; }; + 566475DB1D98319F00FF74B8 /* TextEncodingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475DA1D98319F00FF74B8 /* TextEncodingTests.swift */; }; + 566475DC1D98319F00FF74B8 /* TextEncodingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475DA1D98319F00FF74B8 /* TextEncodingTests.swift */; }; + 566475DD1D98319F00FF74B8 /* TextEncodingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475DA1D98319F00FF74B8 /* TextEncodingTests.swift */; }; + 566475DE1D98319F00FF74B8 /* TextEncodingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475DA1D98319F00FF74B8 /* TextEncodingTests.swift */; }; + 566475DF1D98319F00FF74B8 /* TextEncodingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475DA1D98319F00FF74B8 /* TextEncodingTests.swift */; }; + 566475E01D98319F00FF74B8 /* TextEncodingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475DA1D98319F00FF74B8 /* TextEncodingTests.swift */; }; + 566475E11D98319F00FF74B8 /* TextEncodingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475DA1D98319F00FF74B8 /* TextEncodingTests.swift */; }; + 566475E21D98319F00FF74B8 /* TextEncodingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475DA1D98319F00FF74B8 /* TextEncodingTests.swift */; }; + 566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; + 566AD8B31D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; + 566AD8B41D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; + 566AD8B51D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; + 566AD8B61D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; + 566AD8B71D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 566AD8C71D531BEA002EC1A8 /* SQLTableBuilderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* SQLTableBuilderTests.swift */; }; 566AD8C81D531BEB002EC1A8 /* SQLTableBuilderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* SQLTableBuilderTests.swift */; }; 566AD8C91D531BEB002EC1A8 /* SQLTableBuilderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* SQLTableBuilderTests.swift */; }; @@ -603,11 +659,10 @@ 56AF74721D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */; }; 56AFC97A1CB1A41E00F48B96 /* libsqlcipher.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 560FC5561CB004AD0014AA8E /* libsqlcipher.a */; }; 56AFC9F11CB1A8BB00F48B96 /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; - 56AFC9F21CB1A8BB00F48B96 /* SQLCollation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollation.swift */; }; + 56AFC9F21CB1A8BB00F48B96 /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; 56AFC9F31CB1A8BB00F48B96 /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238711B9C75030082EB20 /* Database.swift */; }; 56AFC9F41CB1A8BB00F48B96 /* CGFloat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1491C672E4000235C62 /* CGFloat.swift */; }; 56AFC9F51CB1A8BB00F48B96 /* Date.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F14F1C672E4000235C62 /* Date.swift */; }; - 56AFC9F61CB1A8BB00F48B96 /* SQLFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18A1C6B1A8700235C62 /* SQLFunction.swift */; }; 56AFC9F71CB1A8BB00F48B96 /* RawRepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1571C672E4000235C62 /* RawRepresentable.swift */; }; 56AFC9F81CB1A8BB00F48B96 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563445041C4A7FD7003D3DC6 /* Utils.swift */; }; 56AFC9F91CB1A8BB00F48B96 /* DatabaseWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363C31C942C37000BE133 /* DatabaseWriter.swift */; }; @@ -617,14 +672,13 @@ 56AFC9FD1CB1A8BB00F48B96 /* NSString.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1521C672E4000235C62 /* NSString.swift */; }; 56AFC9FF1CB1A8BB00F48B96 /* DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */; }; 56AFCA001CB1A8BB00F48B96 /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; - 56AFCA011CB1A8BB00F48B96 /* SQLOperator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18B1C6B1A8700235C62 /* SQLOperator.swift */; }; 56AFCA031CB1A8BB00F48B96 /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableMapping.swift */; }; 56AFCA041CB1A8BB00F48B96 /* DatabaseCoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F14B1C672E4000235C62 /* DatabaseCoder.swift */; }; 56AFCA051CB1A8BB00F48B96 /* NSURL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1531C672E4000235C62 /* NSURL.swift */; }; 56AFCA061CB1A8BB00F48B96 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238701B9C75030082EB20 /* Configuration.swift */; }; 56AFCA071CB1A8BB00F48B96 /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A31C8F625000949E71 /* DatabasePool.swift */; }; 56AFCA081CB1A8BB00F48B96 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238781B9C75030082EB20 /* Statement.swift */; }; - 56AFCA091CB1A8BB00F48B96 /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */; }; + 56AFCA091CB1A8BB00F48B96 /* QueryInterfaceSelectQueryDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */; }; 56AFCA0A1CB1A8BB00F48B96 /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; 56AFCA0B1CB1A8BB00F48B96 /* Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238761B9C75030082EB20 /* Row.swift */; }; 56AFCA0C1CB1A8BB00F48B96 /* DatabaseSchemaCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */; }; @@ -936,6 +990,13 @@ 56FC78671BBAEB8C00CA1285 /* MappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC78641BBAEB8C00CA1285 /* MappingTests.swift */; }; 56FC78681BBAEB8C00CA1285 /* ManagedDataControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC78651BBAEB8C00CA1285 /* ManagedDataControllerTests.swift */; }; 56FC78691BBAEB8C00CA1285 /* ManagedDataControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC78651BBAEB8C00CA1285 /* ManagedDataControllerTests.swift */; }; + 56FC98781D969DEF00E3C842 /* SQLExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression.swift */; }; + 56FC98791D969DEF00E3C842 /* SQLExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression.swift */; }; + 56FC987A1D969DEF00E3C842 /* SQLExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression.swift */; }; + 56FC987B1D969DEF00E3C842 /* SQLExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression.swift */; }; + 56FC987C1D969DEF00E3C842 /* SQLExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression.swift */; }; + 56FC987D1D969DEF00E3C842 /* SQLExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression.swift */; }; + 56FC987E1D969DEF00E3C842 /* SQLExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression.swift */; }; 56FDECE31BB32DFD009AD709 /* MetalRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* MetalRowTests.swift */; }; 56FF45411D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* DeleteByKeyTests.swift */; }; 56FF45421D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* DeleteByKeyTests.swift */; }; @@ -991,10 +1052,8 @@ F3BA80281CFB2891003DC1BA /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; F3BA80291CFB2895003DC1BA /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563445041C4A7FD7003D3DC6 /* Utils.swift */; }; F3BA802B1CFB289B003DC1BA /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; - F3BA802C1CFB289B003DC1BA /* SQLCollation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollation.swift */; }; - F3BA802D1CFB289B003DC1BA /* SQLFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18A1C6B1A8700235C62 /* SQLFunction.swift */; }; - F3BA802E1CFB289B003DC1BA /* SQLOperator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18B1C6B1A8700235C62 /* SQLOperator.swift */; }; - F3BA802F1CFB289B003DC1BA /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */; }; + F3BA802C1CFB289B003DC1BA /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; + F3BA802F1CFB289B003DC1BA /* QueryInterfaceSelectQueryDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */; }; F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; F3BA80311CFB289F003DC1BA /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; F3BA80321CFB28A4003DC1BA /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; @@ -1044,10 +1103,8 @@ F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; F3BA80851CFB2E6C003DC1BA /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563445041C4A7FD7003D3DC6 /* Utils.swift */; }; F3BA80871CFB2E70003DC1BA /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; - F3BA80881CFB2E70003DC1BA /* SQLCollation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollation.swift */; }; - F3BA80891CFB2E70003DC1BA /* SQLFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18A1C6B1A8700235C62 /* SQLFunction.swift */; }; - F3BA808A1CFB2E70003DC1BA /* SQLOperator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18B1C6B1A8700235C62 /* SQLOperator.swift */; }; - F3BA808B1CFB2E70003DC1BA /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */; }; + F3BA80881CFB2E70003DC1BA /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; + F3BA808B1CFB2E70003DC1BA /* QueryInterfaceSelectQueryDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */; }; F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; F3BA808D1CFB2E75003DC1BA /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; F3BA808E1CFB2E7A003DC1BA /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; @@ -1431,10 +1488,8 @@ 5605F1571C672E4000235C62 /* RawRepresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RawRepresentable.swift; sourceTree = ""; }; 5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = ""; }; 5605F1861C69111300235C62 /* StatementInformationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementInformationTests.swift; sourceTree = ""; }; - 5605F1891C6B1A8700235C62 /* SQLCollation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollation.swift; sourceTree = ""; }; - 5605F18A1C6B1A8700235C62 /* SQLFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunction.swift; sourceTree = ""; }; - 5605F18B1C6B1A8700235C62 /* SQLOperator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperator.swift; sourceTree = ""; }; - 5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectQuery.swift; sourceTree = ""; }; + 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollatedExpression.swift; sourceTree = ""; }; + 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceSelectQueryDefinition.swift; sourceTree = ""; }; 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = ""; }; 560A37A31C8F625000949E71 /* DatabasePool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePool.swift; sourceTree = ""; }; 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SerializedDatabase.swift; sourceTree = ""; }; @@ -1495,7 +1550,16 @@ 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+FoundationTests.swift"; sourceTree = ""; }; 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NumericOverflowTests.swift; sourceTree = ""; }; 565F03C11CE5D3AA00DE108F /* AdapterRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AdapterRowTests.swift; sourceTree = ""; }; - 566AD8B11D5318F4002EC1A8 /* SQLTableBuilder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLTableBuilder.swift; sourceTree = ""; }; + 566475991D97D8A000FF74B8 /* SQLCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollection.swift; sourceTree = ""; }; + 566475A11D9810A400FF74B8 /* SQLSelectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectable.swift; sourceTree = ""; }; + 566475A91D9818B100FF74B8 /* GRDB-0-84-0-ConversionHelper.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "GRDB-0-84-0-ConversionHelper.swift"; sourceTree = ""; }; + 566475B11D9819D500FF74B8 /* SQLOrderingTerm.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOrderingTerm.swift; sourceTree = ""; }; + 566475B91D981AD200FF74B8 /* SQLSpecificExpressible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSpecificExpressible.swift; sourceTree = ""; }; + 566475C11D981C5D00FF74B8 /* SQLSelectQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectQuery.swift; sourceTree = ""; }; + 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunctions.swift; sourceTree = ""; }; + 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperators.swift; sourceTree = ""; }; + 566475DA1D98319F00FF74B8 /* TextEncodingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TextEncodingTests.swift; sourceTree = ""; }; + 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinition.swift; sourceTree = ""; }; 566AD8C51D531BE4002EC1A8 /* SQLTableBuilderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLTableBuilderTests.swift; sourceTree = ""; }; 567156151CB142AA007DC145 /* ReadOnlyDatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReadOnlyDatabaseTests.swift; sourceTree = ""; }; 5671566C1CB16729007DC145 /* GRDBCipherOSXEncryptedTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCipherOSXEncryptedTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -1625,6 +1689,7 @@ 56F0B98E1B6001C600A2F135 /* NSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSDateTests.swift; sourceTree = ""; }; 56FC78641BBAEB8C00CA1285 /* MappingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MappingTests.swift; sourceTree = ""; }; 56FC78651BBAEB8C00CA1285 /* ManagedDataControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ManagedDataControllerTests.swift; sourceTree = ""; }; + 56FC98771D969DEF00E3C842 /* SQLExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpression.swift; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* MetalRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MetalRowTests.swift; sourceTree = ""; }; 56FF453F1D2C23BA00F21EF9 /* DeleteByKeyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DeleteByKeyTests.swift; sourceTree = ""; }; 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = ""; }; @@ -1936,11 +2001,16 @@ isa = PBXGroup; children = ( 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, - 5605F1891C6B1A8700235C62 /* SQLCollation.swift */, - 5605F18A1C6B1A8700235C62 /* SQLFunction.swift */, - 5605F18B1C6B1A8700235C62 /* SQLOperator.swift */, - 5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */, - 566AD8B11D5318F4002EC1A8 /* SQLTableBuilder.swift */, + 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */, + 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, + 566475991D97D8A000FF74B8 /* SQLCollection.swift */, + 56FC98771D969DEF00E3C842 /* SQLExpression.swift */, + 566475B11D9819D500FF74B8 /* SQLOrderingTerm.swift */, + 566475A11D9810A400FF74B8 /* SQLSelectable.swift */, + 566475C11D981C5D00FF74B8 /* SQLSelectQuery.swift */, + 566475B91D981AD200FF74B8 /* SQLSpecificExpressible.swift */, + 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */, + 566475C91D981D5E00FF74B8 /* Support */, ); path = QueryInterface; sourceTree = ""; @@ -1973,6 +2043,15 @@ path = Collation; sourceTree = ""; }; + 566475C91D981D5E00FF74B8 /* Support */ = { + isa = PBXGroup; + children = ( + 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */, + 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */, + ); + path = Support; + sourceTree = ""; + }; 566AD8C41D531BD0002EC1A8 /* SQLTableBuilder */ = { isa = PBXGroup; children = ( @@ -2091,6 +2170,7 @@ 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */, 56A238141B9C74A90082EB20 /* InMemoryDatabaseTests.swift */, 567156151CB142AA007DC145 /* ReadOnlyDatabaseTests.swift */, + 566475DA1D98319F00FF74B8 /* TextEncodingTests.swift */, ); path = Database; sourceTree = ""; @@ -2452,6 +2532,7 @@ DC3773F819C8CBB3004FCF85 /* GRDB.h */, DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */, DC3773F719C8CBB3004FCF85 /* Info.plist */, + 566475A91D9818B100FF74B8 /* GRDB-0-84-0-ConversionHelper.swift */, EE578FFC1D84B518004E0D9E /* GRDB-Swift2-ConversionHelper.swift */, ); name = "Supporting Files"; @@ -3266,23 +3347,26 @@ 5636E9BD1D22574100B9B05F /* FetchRequest.swift in Sources */, 56BB6EAA1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, 560FC51C1CB003810014AA8E /* QueryInterfaceRequest.swift in Sources */, - 560FC51D1CB003810014AA8E /* SQLCollation.swift in Sources */, + 560FC51D1CB003810014AA8E /* SQLCollatedExpression.swift in Sources */, + 566475D41D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 560FC51E1CB003810014AA8E /* Utils.swift in Sources */, 560FC51F1CB003810014AA8E /* CGFloat.swift in Sources */, 560FC5201CB003810014AA8E /* Date.swift in Sources */, - 560FC5211CB003810014AA8E /* SQLFunction.swift in Sources */, 560FC5221CB003810014AA8E /* RawRepresentable.swift in Sources */, 560FC5231CB003810014AA8E /* Configuration.swift in Sources */, + 566475CD1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, + 5664759B1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 567404891CEF84C8003ED5CC /* RowAdapter.swift in Sources */, 560FC5241CB003810014AA8E /* DatabaseWriter.swift in Sources */, + 566475C31D981C5D00FF74B8 /* SQLSelectQuery.swift in Sources */, 560FC5251CB003810014AA8E /* DatabaseStore.swift in Sources */, 560FC5261CB003810014AA8E /* SerializedDatabase.swift in Sources */, 560FC5271CB003810014AA8E /* NSString.swift in Sources */, 560FC5291CB003810014AA8E /* DatabaseValueConvertible.swift in Sources */, 56A8C2311D1914540096E9D4 /* UUID.swift in Sources */, 560FC52A1CB003810014AA8E /* DatabaseError.swift in Sources */, + 566475BB1D981AD200FF74B8 /* SQLSpecificExpressible.swift in Sources */, 560FC52B1CB003810014AA8E /* DatabaseValue.swift in Sources */, - 560FC52C1CB003810014AA8E /* SQLOperator.swift in Sources */, 560FC52E1CB003810014AA8E /* Record.swift in Sources */, 560FC52F1CB003810014AA8E /* DatabaseCoder.swift in Sources */, 5657AB101D10899D006283EF /* URL.swift in Sources */, @@ -3290,9 +3374,10 @@ 560FC5311CB003810014AA8E /* TableMapping.swift in Sources */, 560FC5321CB003810014AA8E /* DatabasePool.swift in Sources */, 560FC5331CB003810014AA8E /* Migration.swift in Sources */, - 560FC5341CB003810014AA8E /* SQLSelectQuery.swift in Sources */, + 560FC5341CB003810014AA8E /* QueryInterfaceSelectQueryDefinition.swift in Sources */, 560FC5351CB003810014AA8E /* Statement.swift in Sources */, 5690C3411D23E82A00E59934 /* Data.swift in Sources */, + 56FC98791D969DEF00E3C842 /* SQLExpression.swift in Sources */, 563ABAF81D18824F003B37F3 /* NSUUID.swift in Sources */, 560FC5361CB003810014AA8E /* DatabaseMigrator.swift in Sources */, 560FC5371CB003810014AA8E /* DatabaseSchemaCache.swift in Sources */, @@ -3303,15 +3388,18 @@ 560FC53A1CB003810014AA8E /* NSNull.swift in Sources */, EE578FFE1D84B518004E0D9E /* GRDB-Swift2-ConversionHelper.swift in Sources */, 560FC53B1CB003810014AA8E /* Database.swift in Sources */, - 566AD8B31D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */, + 566AD8B31D5318F4002EC1A8 /* TableDefinition.swift in Sources */, + 566475AB1D9818B100FF74B8 /* GRDB-0-84-0-ConversionHelper.swift in Sources */, 560FC53C1CB003810014AA8E /* DatabaseQueue.swift in Sources */, 560FC53D1CB003810014AA8E /* NSNumber.swift in Sources */, 560FC53F1CB003810014AA8E /* Row.swift in Sources */, 560FC5401CB003810014AA8E /* StandardLibrary.swift in Sources */, 560FC5411CB003810014AA8E /* Persistable.swift in Sources */, + 566475A31D9810A400FF74B8 /* SQLSelectable.swift in Sources */, 5657AABA1D107001006283EF /* NSData.swift in Sources */, 560FC5421CB003810014AA8E /* StatementColumnConvertible.swift in Sources */, 560FC5431CB003810014AA8E /* RowConvertible.swift in Sources */, + 566475B31D9819D500FF74B8 /* SQLOrderingTerm.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -3402,6 +3490,7 @@ 560FC59C1CB00B880014AA8E /* StatementArguments+FoundationTests.swift in Sources */, 5657AB671D108BA9006283EF /* URLTests.swift in Sources */, 560FC59D1CB00B880014AA8E /* TableMapping+QueryInterfaceRequestTests.swift in Sources */, + 566475DC1D98319F00FF74B8 /* TextEncodingTests.swift in Sources */, 5634B0741CF22BEF005360B9 /* FetchRequestTests.swift in Sources */, 560FC59E1CB00B880014AA8E /* NSDateTests.swift in Sources */, 560FC59F1CB00B880014AA8E /* DatabaseTests.swift in Sources */, @@ -3426,10 +3515,12 @@ 565490CE1D5AE252005622CB /* NSNull.swift in Sources */, 565490E41D5AE252005622CB /* TableMapping.swift in Sources */, 565490CF1D5AE252005622CB /* NSNumber.swift in Sources */, + 566475C01D981AD200FF74B8 /* SQLSpecificExpressible.swift in Sources */, 565490E21D5AE252005622CB /* Record.swift in Sources */, 565490C11D5AE236005622CB /* FetchRequest.swift in Sources */, 56F5ABDA1D814330001F60CB /* NSData.swift in Sources */, 565490BD1D5AE236005622CB /* DatabaseStore.swift in Sources */, + 566475A81D9810A400FF74B8 /* SQLSelectable.swift in Sources */, 565490B91D5AE236005622CB /* DatabasePool.swift in Sources */, 565490D81D5AE252005622CB /* DatabaseMigrator.swift in Sources */, 565490C21D5AE236005622CB /* Row.swift in Sources */, @@ -3441,33 +3532,38 @@ 565490D71D5AE252005622CB /* Utils.swift in Sources */, 565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */, EE5790031D84B518004E0D9E /* GRDB-Swift2-ConversionHelper.swift in Sources */, + 566475A01D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 565490BB1D5AE236005622CB /* DatabaseReader.swift in Sources */, 565490C91D5AE252005622CB /* DatabaseCoder.swift in Sources */, 565490C31D5AE236005622CB /* RowAdapter.swift in Sources */, - 565490DD1D5AE252005622CB /* SQLOperator.swift in Sources */, 565490DA1D5AE252005622CB /* QueryInterfaceRequest.swift in Sources */, 565490CA1D5AE252005622CB /* DatabaseDateComponents.swift in Sources */, 565490D01D5AE252005622CB /* NSString.swift in Sources */, 565490D11D5AE252005622CB /* NSURL.swift in Sources */, 565490E31D5AE252005622CB /* RowConvertible.swift in Sources */, - 565490DF1D5AE252005622CB /* SQLTableBuilder.swift in Sources */, + 565490DF1D5AE252005622CB /* TableDefinition.swift in Sources */, 565490B71D5AE236005622CB /* Database.swift in Sources */, 565490C01D5AE236005622CB /* DatabaseWriter.swift in Sources */, 565490C41D5AE236005622CB /* SchedulingWatchdog.swift in Sources */, 565490CC1D5AE252005622CB /* (null) in Sources */, - 565490DB1D5AE252005622CB /* SQLCollation.swift in Sources */, + 566475B01D9818B100FF74B8 /* GRDB-0-84-0-ConversionHelper.swift in Sources */, + 565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */, 565490C61D5AE236005622CB /* Statement.swift in Sources */, 56F5ABD91D814330001F60CB /* Data.swift in Sources */, 565490D41D5AE252005622CB /* (null) in Sources */, + 566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, 565490B61D5AE236005622CB /* Configuration.swift in Sources */, + 566475B81D9819D500FF74B8 /* SQLOrderingTerm.swift in Sources */, 565490E11D5AE252005622CB /* Persistable.swift in Sources */, + 56FC987E1D969DEF00E3C842 /* SQLExpression.swift in Sources */, 565490E01D5AE252005622CB /* FetchedRecordsController.swift in Sources */, 565490C81D5AE252005622CB /* CGFloat.swift in Sources */, 565490D21D5AE252005622CB /* NSUUID.swift in Sources */, - 565490DC1D5AE252005622CB /* SQLFunction.swift in Sources */, 56F5ABDC1D814330001F60CB /* URL.swift in Sources */, + 566475C81D981C5D00FF74B8 /* SQLSelectQuery.swift in Sources */, 565490D31D5AE252005622CB /* (null) in Sources */, - 565490DE1D5AE252005622CB /* SQLSelectQuery.swift in Sources */, + 566475D91D981D5E00FF74B8 /* SQLOperators.swift in Sources */, + 565490DE1D5AE252005622CB /* QueryInterfaceSelectQueryDefinition.swift in Sources */, 56F5ABDD1D814330001F60CB /* UUID.swift in Sources */, 565490CB1D5AE252005622CB /* (null) in Sources */, 565490D61D5AE252005622CB /* StandardLibrary.swift in Sources */, @@ -3582,6 +3678,7 @@ 567156591CB16729007DC145 /* DatabaseTimestampTests.swift in Sources */, 5671565A1CB16729007DC145 /* StatementArguments+FoundationTests.swift in Sources */, 5657AB581D108BA9006283EF /* NSStringTests.swift in Sources */, + 566475DD1D98319F00FF74B8 /* TextEncodingTests.swift in Sources */, 5671565B1CB16729007DC145 /* TableMapping+QueryInterfaceRequestTests.swift in Sources */, 5671565C1CB16729007DC145 /* NSDateTests.swift in Sources */, 5671565D1CB16729007DC145 /* DatabaseTests.swift in Sources */, @@ -3606,23 +3703,26 @@ 5636E9C01D22574100B9B05F /* FetchRequest.swift in Sources */, 56BB6EAD1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, 56AFC9F11CB1A8BB00F48B96 /* QueryInterfaceRequest.swift in Sources */, - 56AFC9F21CB1A8BB00F48B96 /* SQLCollation.swift in Sources */, + 56AFC9F21CB1A8BB00F48B96 /* SQLCollatedExpression.swift in Sources */, + 566475D71D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 56AFC9F31CB1A8BB00F48B96 /* Database.swift in Sources */, 56AFC9F41CB1A8BB00F48B96 /* CGFloat.swift in Sources */, 56AFC9F51CB1A8BB00F48B96 /* Date.swift in Sources */, - 56AFC9F61CB1A8BB00F48B96 /* SQLFunction.swift in Sources */, 56AFC9F71CB1A8BB00F48B96 /* RawRepresentable.swift in Sources */, 56AFC9F81CB1A8BB00F48B96 /* Utils.swift in Sources */, + 566475D01D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, + 5664759E1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 5674048B1CEF84C8003ED5CC /* RowAdapter.swift in Sources */, 56AFC9F91CB1A8BB00F48B96 /* DatabaseWriter.swift in Sources */, + 566475C61D981C5D00FF74B8 /* SQLSelectQuery.swift in Sources */, 56AFC9FA1CB1A8BB00F48B96 /* DatabaseStore.swift in Sources */, 56AFC9FB1CB1A8BB00F48B96 /* SerializedDatabase.swift in Sources */, 56AFC9FC1CB1A8BB00F48B96 /* DatabaseMigrator.swift in Sources */, 56AFC9FD1CB1A8BB00F48B96 /* NSString.swift in Sources */, 56A8C2341D1914540096E9D4 /* UUID.swift in Sources */, 56AFC9FF1CB1A8BB00F48B96 /* DatabaseValueConvertible.swift in Sources */, + 566475BE1D981AD200FF74B8 /* SQLSpecificExpressible.swift in Sources */, 56AFCA001CB1A8BB00F48B96 /* Record.swift in Sources */, - 56AFCA011CB1A8BB00F48B96 /* SQLOperator.swift in Sources */, 56AFCA031CB1A8BB00F48B96 /* TableMapping.swift in Sources */, 56AFCA041CB1A8BB00F48B96 /* DatabaseCoder.swift in Sources */, 5657AB131D10899D006283EF /* URL.swift in Sources */, @@ -3630,9 +3730,10 @@ 56AFCA061CB1A8BB00F48B96 /* Configuration.swift in Sources */, 56AFCA071CB1A8BB00F48B96 /* DatabasePool.swift in Sources */, 56AFCA081CB1A8BB00F48B96 /* Statement.swift in Sources */, - 56AFCA091CB1A8BB00F48B96 /* SQLSelectQuery.swift in Sources */, + 56AFCA091CB1A8BB00F48B96 /* QueryInterfaceSelectQueryDefinition.swift in Sources */, 56AFCA0A1CB1A8BB00F48B96 /* Migration.swift in Sources */, 5690C3441D23E82A00E59934 /* Data.swift in Sources */, + 56FC987C1D969DEF00E3C842 /* SQLExpression.swift in Sources */, 563ABAFB1D18824F003B37F3 /* NSUUID.swift in Sources */, 56AFCA0B1CB1A8BB00F48B96 /* Row.swift in Sources */, 56AFCA0C1CB1A8BB00F48B96 /* DatabaseSchemaCache.swift in Sources */, @@ -3643,15 +3744,18 @@ 56AFCA101CB1A8BB00F48B96 /* DatabaseQueue.swift in Sources */, EE5790011D84B518004E0D9E /* GRDB-Swift2-ConversionHelper.swift in Sources */, 56AFCA111CB1A8BB00F48B96 /* DatabaseError.swift in Sources */, - 566AD8B61D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */, + 566AD8B61D5318F4002EC1A8 /* TableDefinition.swift in Sources */, + 566475AE1D9818B100FF74B8 /* GRDB-0-84-0-ConversionHelper.swift in Sources */, 56AFCA121CB1A8BB00F48B96 /* NSNumber.swift in Sources */, 56AFCA141CB1A8BB00F48B96 /* StandardLibrary.swift in Sources */, 56AFCA151CB1A8BB00F48B96 /* Persistable.swift in Sources */, 56AFCA161CB1A8BB00F48B96 /* StatementColumnConvertible.swift in Sources */, 56AFCA171CB1A8BB00F48B96 /* RowConvertible.swift in Sources */, + 566475A61D9810A400FF74B8 /* SQLSelectable.swift in Sources */, 5657AABD1D107001006283EF /* NSData.swift in Sources */, 56AFCA181CB1A8BB00F48B96 /* FetchedRecordsController.swift in Sources */, 56AFCA191CB1A8BB00F48B96 /* DatabaseValue.swift in Sources */, + 566475B61D9819D500FF74B8 /* SQLOrderingTerm.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -3717,6 +3821,7 @@ 56AFCA581CB1AA9900F48B96 /* Row+FoundationTests.swift in Sources */, 569178411CED8E0C00E179EA /* FetchedRecordsControllerTests.swift in Sources */, 56AFCA5A1CB1AA9900F48B96 /* RecordSubClassTests.swift in Sources */, + 566475E01D98319F00FF74B8 /* TextEncodingTests.swift in Sources */, 56A4CDB51D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 56AFCA5B1CB1AA9900F48B96 /* DatabaseValueTests.swift in Sources */, 56AFCA5C1CB1AA9900F48B96 /* ReadOnlyDatabaseTests.swift in Sources */, @@ -3822,6 +3927,7 @@ 56AFCAAF1CB1ABC800F48B96 /* DatabasePoolConcurrencyTests.swift in Sources */, 56AFCAB01CB1ABC800F48B96 /* TransactionObserverTests.swift in Sources */, 56AFCAB11CB1ABC800F48B96 /* Row+FoundationTests.swift in Sources */, + 566475E11D98319F00FF74B8 /* TextEncodingTests.swift in Sources */, 56A4CDB61D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 5657AB4C1D108BA9006283EF /* NSNullTests.swift in Sources */, 56AFCAB31CB1ABC800F48B96 /* RecordSubClassTests.swift in Sources */, @@ -3872,23 +3978,26 @@ 5636E9BF1D22574100B9B05F /* FetchRequest.swift in Sources */, 56BB6EAC1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, 56300B791C53F592005A543B /* QueryInterfaceRequest.swift in Sources */, - 5605F18E1C6B1A8700235C62 /* SQLCollation.swift in Sources */, + 5605F18E1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */, + 566475D61D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 56A2387E1B9C75030082EB20 /* Database.swift in Sources */, 5605F15A1C672E4000235C62 /* CGFloat.swift in Sources */, 5605F1641C672E4000235C62 /* Date.swift in Sources */, - 5605F1901C6B1A8700235C62 /* SQLFunction.swift in Sources */, 5605F1721C672E4000235C62 /* RawRepresentable.swift in Sources */, 563445061C4A7FD7003D3DC6 /* Utils.swift in Sources */, + 566475CF1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, + 5664759D1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 5674048A1CEF84C8003ED5CC /* RowAdapter.swift in Sources */, 563363C51C942C37000BE133 /* DatabaseWriter.swift in Sources */, + 566475C51D981C5D00FF74B8 /* SQLSelectQuery.swift in Sources */, 563363D91C95787F000BE133 /* DatabaseStore.swift in Sources */, 560A37A81C8FF6E500949E71 /* SerializedDatabase.swift in Sources */, 56A238941B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */, 5605F16A1C672E4000235C62 /* NSString.swift in Sources */, 56A8C2331D1914540096E9D4 /* UUID.swift in Sources */, 560D92411C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */, + 566475BD1D981AD200FF74B8 /* SQLSpecificExpressible.swift in Sources */, 56A238A51B9C753B0082EB20 /* Record.swift in Sources */, - 5605F1921C6B1A8700235C62 /* SQLOperator.swift in Sources */, 560D924C1C672C4B00F4F92B /* TableMapping.swift in Sources */, 5605F15C1C672E4000235C62 /* DatabaseCoder.swift in Sources */, 5657AB121D10899D006283EF /* URL.swift in Sources */, @@ -3896,9 +4005,10 @@ 56A2387C1B9C75030082EB20 /* Configuration.swift in Sources */, 560A37A51C8F625000949E71 /* DatabasePool.swift in Sources */, 56A2388C1B9C75030082EB20 /* Statement.swift in Sources */, - 5605F1941C6B1A8700235C62 /* SQLSelectQuery.swift in Sources */, + 5605F1941C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift in Sources */, 56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */, 5690C3431D23E82A00E59934 /* Data.swift in Sources */, + 56FC987B1D969DEF00E3C842 /* SQLExpression.swift in Sources */, 563ABAFA1D18824F003B37F3 /* NSUUID.swift in Sources */, 56A238881B9C75030082EB20 /* Row.swift in Sources */, 569531201C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, @@ -3909,15 +4019,18 @@ 56A238841B9C75030082EB20 /* DatabaseQueue.swift in Sources */, EE5790001D84B518004E0D9E /* GRDB-Swift2-ConversionHelper.swift in Sources */, 56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */, - 566AD8B51D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */, + 566AD8B51D5318F4002EC1A8 /* TableDefinition.swift in Sources */, + 566475AD1D9818B100FF74B8 /* GRDB-0-84-0-ConversionHelper.swift in Sources */, 5605F1681C672E4000235C62 /* NSNumber.swift in Sources */, 5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */, 560D92481C672C4B00F4F92B /* Persistable.swift in Sources */, 560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */, 560D924A1C672C4B00F4F92B /* RowConvertible.swift in Sources */, + 566475A51D9810A400FF74B8 /* SQLSelectable.swift in Sources */, 5657AABC1D107001006283EF /* NSData.swift in Sources */, 31A778841C6A4E0600F507F6 /* FetchedRecordsController.swift in Sources */, 56A238861B9C75030082EB20 /* DatabaseValue.swift in Sources */, + 566475B51D9819D500FF74B8 /* SQLOrderingTerm.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -4008,6 +4121,7 @@ 56A238B71B9CA2590082EB20 /* DatabaseTimestampTests.swift in Sources */, 565D5D751BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */, 5657AB5A1D108BA9006283EF /* NSStringTests.swift in Sources */, + 566475DF1D98319F00FF74B8 /* TextEncodingTests.swift in Sources */, 56300B6C1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift in Sources */, 56F0B9921B6001C600A2F135 /* NSDateTests.swift in Sources */, 56A238381B9C74A90082EB20 /* DatabaseTests.swift in Sources */, @@ -4078,6 +4192,7 @@ 56D496711D81309E008276D7 /* PrimaryKeySingleTests.swift in Sources */, 56D496611D81304E008276D7 /* Row+FoundationTests.swift in Sources */, 56D496C41D813767008276D7 /* DatabaseQueueTests.swift in Sources */, + 566475DB1D98319F00FF74B8 /* TextEncodingTests.swift in Sources */, 56D496851D813147008276D7 /* StatementArgumentsTests.swift in Sources */, 56D496B81D813465008276D7 /* DataMemoryTests.swift in Sources */, 56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */, @@ -4128,23 +4243,26 @@ 5636E9BC1D22574100B9B05F /* FetchRequest.swift in Sources */, 56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, 56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */, - 5605F18D1C6B1A8700235C62 /* SQLCollation.swift in Sources */, + 5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */, + 566475D31D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 563445051C4A7FD7003D3DC6 /* Utils.swift in Sources */, 5605F1591C672E4000235C62 /* CGFloat.swift in Sources */, 5605F1631C672E4000235C62 /* Date.swift in Sources */, - 5605F18F1C6B1A8700235C62 /* SQLFunction.swift in Sources */, 5605F1711C672E4000235C62 /* RawRepresentable.swift in Sources */, 56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */, + 566475CC1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, + 5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */, 563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */, + 566475C21D981C5D00FF74B8 /* SQLSelectQuery.swift in Sources */, 563363D81C95787F000BE133 /* DatabaseStore.swift in Sources */, 560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */, 5605F1691C672E4000235C62 /* NSString.swift in Sources */, 560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */, 56A8C2301D1914540096E9D4 /* UUID.swift in Sources */, 56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */, + 566475BA1D981AD200FF74B8 /* SQLSpecificExpressible.swift in Sources */, 56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */, - 5605F1911C6B1A8700235C62 /* SQLOperator.swift in Sources */, 56A238A41B9C753B0082EB20 /* Record.swift in Sources */, 5605F15B1C672E4000235C62 /* DatabaseCoder.swift in Sources */, 5657AB0F1D10899D006283EF /* URL.swift in Sources */, @@ -4152,9 +4270,10 @@ 560D924B1C672C4B00F4F92B /* TableMapping.swift in Sources */, 560A37A41C8F625000949E71 /* DatabasePool.swift in Sources */, 56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */, - 5605F1931C6B1A8700235C62 /* SQLSelectQuery.swift in Sources */, + 5605F1931C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift in Sources */, 56A2388B1B9C75030082EB20 /* Statement.swift in Sources */, 5690C3401D23E82A00E59934 /* Data.swift in Sources */, + 56FC98781D969DEF00E3C842 /* SQLExpression.swift in Sources */, 563ABAF71D18824F003B37F3 /* NSUUID.swift in Sources */, 56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */, 5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, @@ -4165,15 +4284,18 @@ 5605F1651C672E4000235C62 /* NSNull.swift in Sources */, EE578FFD1D84B518004E0D9E /* GRDB-Swift2-ConversionHelper.swift in Sources */, 56A2387D1B9C75030082EB20 /* Database.swift in Sources */, - 566AD8B21D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */, + 566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */, + 566475AA1D9818B100FF74B8 /* GRDB-0-84-0-ConversionHelper.swift in Sources */, 56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */, 5605F1671C672E4000235C62 /* NSNumber.swift in Sources */, 56A238871B9C75030082EB20 /* Row.swift in Sources */, 5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */, 560D92471C672C4B00F4F92B /* Persistable.swift in Sources */, + 566475A21D9810A400FF74B8 /* SQLSelectable.swift in Sources */, 5657AAB91D107001006283EF /* NSData.swift in Sources */, 560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */, 560D92491C672C4B00F4F92B /* RowConvertible.swift in Sources */, + 566475B21D9819D500FF74B8 /* SQLOrderingTerm.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -4185,21 +4307,25 @@ F3BA801B1CFB2886003DC1BA /* CGFloat.swift in Sources */, 56BB6EAE1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, F3BA801A1CFB2876003DC1BA /* StatementColumnConvertible.swift in Sources */, + 566475D81D981D5E00FF74B8 /* SQLOperators.swift in Sources */, F3BA80181CFB2876003DC1BA /* SerializedDatabase.swift in Sources */, F3BA800D1CFB2871003DC1BA /* DatabasePool.swift in Sources */, F3BA800B1CFB286D003DC1BA /* Database.swift in Sources */, F3BA80341CFB28A4003DC1BA /* Record.swift in Sources */, F3BA80161CFB2876003DC1BA /* Row.swift in Sources */, F3BA80101CFB2876003DC1BA /* DatabaseReader.swift in Sources */, + 566475D11D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, + 5664759F1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, F3BA802B1CFB289B003DC1BA /* QueryInterfaceRequest.swift in Sources */, F3BA80131CFB2876003DC1BA /* DatabaseValue.swift in Sources */, + 566475C71D981C5D00FF74B8 /* SQLSelectQuery.swift in Sources */, F3BA80171CFB2876003DC1BA /* RowAdapter.swift in Sources */, - F3BA802F1CFB289B003DC1BA /* SQLSelectQuery.swift in Sources */, + F3BA802F1CFB289B003DC1BA /* QueryInterfaceSelectQueryDefinition.swift in Sources */, F3BA80201CFB288C003DC1BA /* Date.swift in Sources */, 56A8C2351D1914540096E9D4 /* UUID.swift in Sources */, F3BA80151CFB2876003DC1BA /* DatabaseWriter.swift in Sources */, F3BA800A1CFB286A003DC1BA /* Configuration.swift in Sources */, - F3BA802D1CFB289B003DC1BA /* SQLFunction.swift in Sources */, + 566475BF1D981AD200FF74B8 /* SQLSpecificExpressible.swift in Sources */, F3BA80311CFB289F003DC1BA /* Migration.swift in Sources */, F3BA801D1CFB288C003DC1BA /* DatabaseDateComponents.swift in Sources */, 5657AB141D10899D006283EF /* URL.swift in Sources */, @@ -4208,9 +4334,9 @@ F3BA80221CFB288C003DC1BA /* NSNumber.swift in Sources */, F3BA80321CFB28A4003DC1BA /* FetchedRecordsController.swift in Sources */, F3BA80231CFB288C003DC1BA /* NSString.swift in Sources */, - F3BA802E1CFB289B003DC1BA /* SQLOperator.swift in Sources */, 563ABAFC1D18824F003B37F3 /* NSUUID.swift in Sources */, 5690C3451D23E82A00E59934 /* Data.swift in Sources */, + 56FC987D1D969DEF00E3C842 /* SQLExpression.swift in Sources */, F3BA80111CFB2876003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80281CFB2891003DC1BA /* StandardLibrary.swift in Sources */, F3BA80331CFB28A4003DC1BA /* Persistable.swift in Sources */, @@ -4220,16 +4346,19 @@ F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */, F3BA80141CFB2876003DC1BA /* DatabaseValueConvertible.swift in Sources */, EE5790021D84B518004E0D9E /* GRDB-Swift2-ConversionHelper.swift in Sources */, - 566AD8B71D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */, + 566AD8B71D5318F4002EC1A8 /* TableDefinition.swift in Sources */, F3BA80121CFB2876003DC1BA /* DatabaseStore.swift in Sources */, - F3BA802C1CFB289B003DC1BA /* SQLCollation.swift in Sources */, + 566475AF1D9818B100FF74B8 /* GRDB-0-84-0-ConversionHelper.swift in Sources */, + F3BA802C1CFB289B003DC1BA /* SQLCollatedExpression.swift in Sources */, F3BA80241CFB288C003DC1BA /* NSURL.swift in Sources */, F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */, F3BA80361CFB28A4003DC1BA /* TableMapping.swift in Sources */, F3BA80271CFB2891003DC1BA /* RawRepresentable.swift in Sources */, + 566475A71D9810A400FF74B8 /* SQLSelectable.swift in Sources */, 5657AABE1D107001006283EF /* NSData.swift in Sources */, F3BA800E1CFB2876003DC1BA /* DatabaseQueue.swift in Sources */, F3BA80191CFB2876003DC1BA /* Statement.swift in Sources */, + 566475B71D9819D500FF74B8 /* SQLOrderingTerm.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -4320,6 +4449,7 @@ F3BA80DB1CFB300E003DC1BA /* DatabaseValueConversionTests.swift in Sources */, 5657AB5D1D108BA9006283EF /* NSStringTests.swift in Sources */, F3BA81241CFB3063003DC1BA /* PrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, + 566475E21D98319F00FF74B8 /* TextEncodingTests.swift in Sources */, F3BA80E81CFB3016003DC1BA /* DictionaryRowTests.swift in Sources */, F3BA80B41CFB2FC9003DC1BA /* ReadOnlyDatabaseTests.swift in Sources */, F3BA81011CFB3032003DC1BA /* CGFloatTests.swift in Sources */, @@ -4345,21 +4475,25 @@ F3BA80771CFB2E5C003DC1BA /* CGFloat.swift in Sources */, 56BB6EAB1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, F3BA80761CFB2E55003DC1BA /* StatementColumnConvertible.swift in Sources */, + 566475D51D981D5E00FF74B8 /* SQLOperators.swift in Sources */, F3BA80741CFB2E55003DC1BA /* SerializedDatabase.swift in Sources */, F3BA80691CFB2E55003DC1BA /* DatabasePool.swift in Sources */, F3BA80671CFB2E55003DC1BA /* Database.swift in Sources */, F3BA80901CFB2E7A003DC1BA /* Record.swift in Sources */, F3BA80721CFB2E55003DC1BA /* Row.swift in Sources */, F3BA806C1CFB2E55003DC1BA /* DatabaseReader.swift in Sources */, + 566475CE1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, + 5664759C1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, F3BA80871CFB2E70003DC1BA /* QueryInterfaceRequest.swift in Sources */, F3BA806F1CFB2E55003DC1BA /* DatabaseValue.swift in Sources */, + 566475C41D981C5D00FF74B8 /* SQLSelectQuery.swift in Sources */, F3BA80731CFB2E55003DC1BA /* RowAdapter.swift in Sources */, - F3BA808B1CFB2E70003DC1BA /* SQLSelectQuery.swift in Sources */, + F3BA808B1CFB2E70003DC1BA /* QueryInterfaceSelectQueryDefinition.swift in Sources */, F3BA807C1CFB2E61003DC1BA /* Date.swift in Sources */, 56A8C2321D1914540096E9D4 /* UUID.swift in Sources */, F3BA80711CFB2E55003DC1BA /* DatabaseWriter.swift in Sources */, F3BA80661CFB2E55003DC1BA /* Configuration.swift in Sources */, - F3BA80891CFB2E70003DC1BA /* SQLFunction.swift in Sources */, + 566475BC1D981AD200FF74B8 /* SQLSpecificExpressible.swift in Sources */, F3BA808D1CFB2E75003DC1BA /* Migration.swift in Sources */, F3BA80791CFB2E61003DC1BA /* DatabaseDateComponents.swift in Sources */, 5657AB111D10899D006283EF /* URL.swift in Sources */, @@ -4368,9 +4502,9 @@ F3BA807E1CFB2E61003DC1BA /* NSNumber.swift in Sources */, F3BA808E1CFB2E7A003DC1BA /* FetchedRecordsController.swift in Sources */, F3BA807F1CFB2E61003DC1BA /* NSString.swift in Sources */, - F3BA808A1CFB2E70003DC1BA /* SQLOperator.swift in Sources */, 563ABAF91D18824F003B37F3 /* NSUUID.swift in Sources */, 5690C3421D23E82A00E59934 /* Data.swift in Sources */, + 56FC987A1D969DEF00E3C842 /* SQLExpression.swift in Sources */, F3BA806D1CFB2E55003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */, F3BA808F1CFB2E7A003DC1BA /* Persistable.swift in Sources */, @@ -4380,16 +4514,19 @@ F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */, F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */, EE578FFF1D84B518004E0D9E /* GRDB-Swift2-ConversionHelper.swift in Sources */, - 566AD8B41D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */, + 566AD8B41D5318F4002EC1A8 /* TableDefinition.swift in Sources */, F3BA806E1CFB2E55003DC1BA /* DatabaseStore.swift in Sources */, - F3BA80881CFB2E70003DC1BA /* SQLCollation.swift in Sources */, + 566475AC1D9818B100FF74B8 /* GRDB-0-84-0-ConversionHelper.swift in Sources */, + F3BA80881CFB2E70003DC1BA /* SQLCollatedExpression.swift in Sources */, F3BA80801CFB2E61003DC1BA /* NSURL.swift in Sources */, F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */, F3BA80921CFB2E7A003DC1BA /* TableMapping.swift in Sources */, F3BA80831CFB2E67003DC1BA /* RawRepresentable.swift in Sources */, + 566475A41D9810A400FF74B8 /* SQLSelectable.swift in Sources */, 5657AABB1D107001006283EF /* NSData.swift in Sources */, F3BA806A1CFB2E55003DC1BA /* DatabaseQueue.swift in Sources */, F3BA80751CFB2E55003DC1BA /* Statement.swift in Sources */, + 566475B41D9819D500FF74B8 /* SQLOrderingTerm.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -4449,6 +4586,7 @@ F3BA80F21CFB301A003DC1BA /* SavepointTests.swift in Sources */, F3BA80B81CFB2FCD003DC1BA /* DatabaseErrorTests.swift in Sources */, F3BA80FA1CFB3021003DC1BA /* SelectStatementTests.swift in Sources */, + 566475DE1D98319F00FF74B8 /* TextEncodingTests.swift in Sources */, F3BA81191CFB305F003DC1BA /* QueryInterfaceRequestTests.swift in Sources */, F3BA812F1CFB3064003DC1BA /* PrimaryKeyNoneTests.swift in Sources */, 5690C33A1D23E7D200E59934 /* DateTests.swift in Sources */, diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 83ea72a66..e2ff00162 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -38,6 +38,13 @@ public struct Configuration { /// Default: nil public var trace: TraceFunction? + /// The text encoding used by the main database + /// + /// Default: UTF-8 + /// + /// See https://www.sqlite.org/pragma.html#pragma_encoding + public var textEncoding: Database.TextEncoding = .utf8 + // MARK: - Encryption diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 4f2c83e8b..bb4d17cfd 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -92,6 +92,135 @@ public final class Database { case truncate = 3 // SQLITE_CHECKPOINT_TRUNCATE } + /// A built-in SQLite collation. + /// + /// See https://www.sqlite.org/datatype3.html#collation + public struct CollationName : RawRepresentable, Hashable { + public let rawValue: String + + public init(rawValue: String) { + self.rawValue = rawValue + } + + public init(_ rawValue: String) { + self.rawValue = rawValue + } + + public var hashValue: Int { + return rawValue.hashValue + } + + /// The `BINARY` built-in SQL collation + public static let binary = CollationName("BINARY") + + /// The `NOCASE` built-in SQL collation + public static let nocase = CollationName("NOCASE") + + /// The `RTRIM` built-in SQL collation + public static let rtrim = CollationName("RTRIM") + } + + /// An SQLite conflict resolution. + /// + /// See https://www.sqlite.org/lang_conflict.html. + public enum ConflictResolution : String { + case rollback = "ROLLBACK" + case abort = "ABORT" + case fail = "FAIL" + case ignore = "IGNORE" + case replace = "REPLACE" + } + + /// An SQL column type. + /// + /// try db.create(table: "persons") { t in + /// t.column("id", .integer).primaryKey() + /// t.column("title", .text) + /// } + /// + /// See https://www.sqlite.org/datatype3.html + public struct ColumnType : RawRepresentable, Hashable { + public let rawValue: String + + public init(rawValue: String) { + self.rawValue = rawValue + } + + public init(_ rawValue: String) { + self.rawValue = rawValue + } + + public var hashValue: Int { + return rawValue.hashValue + } + + /// The `TEXT` SQL column type + public static let text = ColumnType("TEXT") + + /// The `INTEGER` SQL column type + public static let integer = ColumnType("INTEGER") + + /// The `DOUBLE` SQL column type + public static let double = ColumnType("DOUBLE") + + /// The `NUMERIC` SQL column type + public static let numeric = ColumnType("NUMERIC") + + /// The `BOOLEAN` SQL column type + public static let boolean = ColumnType("BOOLEAN") + + /// The `BLOB` SQL column type + public static let blob = ColumnType("BLOB") + + /// The `DATE` SQL column type + public static let date = ColumnType("DATE") + + /// The `DATETIME` SQL column type + public static let datetime = ColumnType("DATETIME") + } + + /// A database text encoding + /// + /// See https://www.sqlite.org/pragma.html#pragma_encoding + public struct TextEncoding : RawRepresentable, Hashable { + public let rawValue: String + + public init(rawValue: String) { + self.rawValue = rawValue + } + + public init(_ rawValue: String) { + self.rawValue = rawValue + } + + public var hashValue: Int { + return rawValue.hashValue + } + + /// The `UTF-8` database encoding + public static let utf8 = TextEncoding("UTF-8") + + /// The `UTF-16` database encoding + public static let utf16 = TextEncoding("UTF-16") + + /// The `UTF-16le` database encoding + public static let utf16le = TextEncoding("UTF-16le") + + /// The `UTF-16be` database encoding + public static let utf16be = TextEncoding("UTF-16be") + } + + + /// A foreign key action. + /// + /// See https://www.sqlite.org/foreignkeys.html + public enum ForeignKeyAction : String { + case cascade = "CASCADE" + case restrict = "RESTRICT" + case setNull = "SET NULL" + case setDefault = "SET DEFAULT" + } + /// An SQLite threading mode. See https://www.sqlite.org/threadsafe.html. enum ThreadingMode { case `default` @@ -212,6 +341,7 @@ public final class Database { throw DatabaseError(code: code, message: String(cString: sqlite3_errmsg(sqliteConnection))) } + let textEncoding: TextEncoding do { #if SQLITE_HAS_CODEC if let passphrase = configuration.passphrase { @@ -224,15 +354,57 @@ public final class Database { // // So let's fail early if file is not a database, or encrypted with // another passphrase. - let readCode = sqlite3_exec(sqliteConnection, "SELECT * FROM sqlite_master LIMIT 1", nil, nil, nil) - guard readCode == SQLITE_OK else { - throw DatabaseError(code: readCode, message: String(cString: sqlite3_errmsg(sqliteConnection))) + do { + // TODO: this would be much easier if we would disable SchedulingWatchDog + let code = sqlite3_exec(sqliteConnection, "SELECT * FROM sqlite_master LIMIT 1", nil, nil, nil) + guard code == SQLITE_OK else { + throw DatabaseError(code: code, message: String(cString: sqlite3_errmsg(sqliteConnection))) + } + } + + // Set database encoding, if not set yet + do { + // TODO: this would be much easier if we would disable SchedulingWatchDog + let code = sqlite3_exec(sqliteConnection, "PRAGMA encoding = '\(configuration.textEncoding.rawValue)'", nil, nil, nil) + guard code == SQLITE_OK else { + throw DatabaseError(code: code, message: String(cString: sqlite3_errmsg(sqliteConnection))) + } + } + + // Read database encoding, and update configuration + do { + // TODO: this would be much easier if we would disable SchedulingWatchDog + var statement: SQLiteStatement? = nil + let code = sqlite3_prepare_v2(sqliteConnection, "PRAGMA encoding", -1, &statement, nil) + guard code == SQLITE_OK else { + throw DatabaseError(code: code, message: String(cString: sqlite3_errmsg(sqliteConnection))) + } + defer { + sqlite3_finalize(statement) + } + switch sqlite3_step(statement) { + case SQLITE_DONE: + // Weird. Don't crash but log + NSLog("GRDB could not read text encoding of database at path: %@", NSString(string: path)) + textEncoding = configuration.textEncoding + case SQLITE_ROW: + textEncoding = TextEncoding(String(cString: sqlite3_column_text(statement, 0)!)) + case let code: + throw DatabaseError(code: code, message: String(cString: sqlite3_errmsg(sqliteConnection))) + } } } catch { closeConnection(sqliteConnection!) throw error } + // Store real textEncoding in configuration + if textEncoding != configuration.textEncoding { + NSLog("GRDB warning: text encoding of database at path %@ is %@, not %@", NSString(string: path), NSString(string: textEncoding.rawValue), NSString(string: configuration.textEncoding.rawValue)) + } + var configuration = configuration + configuration.textEncoding = textEncoding + self.configuration = configuration self.schemaCache = schemaCache self.sqliteConnection = sqliteConnection! diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index 6799c06eb..04242c4fc 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -245,6 +245,18 @@ extension DatabaseValue : DatabaseValueConvertible { public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> DatabaseValue? { return databaseValue } + + /// This property is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// See SQLExpression.sqlExpression + public var sqlExpression: SQLExpression { + return self + } } diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 6125e4660..4161b8adb 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -1,27 +1,16 @@ // MARK: - SQLExpressible -/// This protocol is an implementation detail of the query interface. -/// Do not use it directly. -/// -/// See https://github.com/groue/GRDB.swift/#the-query-interface -public protocol _SQLExpressible { - - /// This property is an implementation detail of the query interface. - /// Do not use it directly. - /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface - var sqlExpression: _SQLExpression { get } -} - /// The protocol for all types that can be turned into an SQL expression. /// /// It is adopted by protocols like DatabaseValueConvertible, and types /// like Column. /// -/// Do not declare adoption of SQLExpressible on any type: you would have to -/// use semi-private APIs and types, whose name start with an underscore, that -/// are subject to change as GRDB evolves. -public protocol SQLExpressible : _SQLExpressible { +/// See https://github.com/groue/GRDB.swift/#the-query-interface +public protocol SQLExpressible { + /// Returns an SQLExpression + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + var sqlExpression: SQLExpression { get } } @@ -59,8 +48,12 @@ extension DatabaseValueConvertible { /// Do not use it directly. /// /// See https://github.com/groue/GRDB.swift/#the-query-interface - public var sqlExpression: _SQLExpression { - return .value(self) + /// + /// # Low Level Query Interface + /// + /// See SQLExpression.sqlExpression + public var sqlExpression: SQLExpression { + return databaseValue } } @@ -414,27 +407,3 @@ extension Optional where Wrapped: DatabaseValueConvertible { return fetchAll(db, SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter)) } } - - -extension DatabaseValueConvertible { - /// self as an SQL literal, with proper escaping - /// - /// "'foo'".sqlLiteral // "'''foo'''" - var sqlLiteral: String { - // Slow but reliable implementation. - return escapingConnection.inDatabase { db in - _ = Row.fetch(db, "SELECT ?", arguments: [self]).makeIterator().next() - let index = lastEscapingSQL.index(lastEscapingSQL.startIndex, offsetBy: 7) - assert(lastEscapingSQL.substring(to: index) == "SELECT ") - return lastEscapingSQL.substring(from: index) - } - } -} - -// Suport for DatabaseValueConvertible.sqlLiteral -private var lastEscapingSQL: String = "" -private let escapingConnection: DatabaseQueue = { - var configuration = Configuration() - configuration.trace = { lastEscapingSQL = $0 } - return DatabaseQueue(configuration: configuration) -}() diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 75b7e9154..099ed8e83 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -131,9 +131,9 @@ public class Statement { var valuesIterator = arguments.values.makeIterator() for (index, argumentName) in sqliteArgumentNames.enumerated() { if let argumentName = argumentName, let value = arguments.namedValues[argumentName] { - try! bind(databaseValue: value?.databaseValue ?? .null, at: index) + try! bind(databaseValue: value, at: index) } else if let value = valuesIterator.next() { - try! bind(databaseValue: value?.databaseValue ?? .null, at: index) + try! bind(databaseValue: value, at: index) } else { try! bind(databaseValue: .null, at: index) } @@ -462,7 +462,7 @@ public struct StatementArguments { /// - parameter sequence: A sequence of DatabaseValueConvertible values. /// - returns: A StatementArguments. public init(_ sequence: Sequence) where Sequence.Iterator.Element == DatabaseValueConvertible? { - values = Array(sequence) + values = sequence.map { $0?.databaseValue ?? .null } } /// Initializes arguments from a sequence of optional values. @@ -473,7 +473,7 @@ public struct StatementArguments { /// - parameter sequence: A sequence of DatabaseValueConvertible values. /// - returns: A StatementArguments. public init(_ sequence: Sequence) where Sequence.Iterator.Element: DatabaseValueConvertible { - values = sequence.map { $0 } + values = sequence.map { $0.databaseValue } } /// Initializes arguments from [Any]. @@ -505,7 +505,7 @@ public struct StatementArguments { /// - parameter sequence: A sequence of (key, value) pairs /// - returns: A StatementArguments. public init(_ dictionary: [String: DatabaseValueConvertible?]) { - namedValues = dictionary + namedValues = Dictionary(keys: dictionary.keys) { dictionary[$0]!?.databaseValue ?? .null } } /// Initializes arguments from a sequence of (key, value) pairs, such as @@ -517,7 +517,7 @@ public struct StatementArguments { /// - parameter sequence: A sequence of (key, value) pairs /// - returns: A StatementArguments. public init(_ sequence: Sequence) where Sequence.Iterator.Element == (String, DatabaseValueConvertible?) { - namedValues = Dictionary(keyValueSequence: sequence) + namedValues = Dictionary(keyValueSequence: sequence.map { ($0, $1?.databaseValue ?? .null) }) } /// Initializes arguments from [AnyHashable: Any]. @@ -544,8 +544,8 @@ public struct StatementArguments { // MARK: Not Public - var values: [DatabaseValueConvertible?] = [] - var namedValues: [String: DatabaseValueConvertible?] = [:] + var values: [DatabaseValue] = [] + var namedValues: [String: DatabaseValue] = [:] init() { } @@ -554,18 +554,18 @@ public struct StatementArguments { let initialValuesCount = values.count let bindings = try statement.sqliteArgumentNames.map { argumentName -> DatabaseValue in if let argumentName = argumentName { - if let value = namedValues[argumentName] { - return value?.databaseValue ?? .null + if let databaseValue = namedValues[argumentName] { + return databaseValue } else if values.isEmpty { throw DatabaseError(code: SQLITE_MISUSE, message: "missing statement argument: \(argumentName)", sql: statement.sql, arguments: nil) } else { - return values.removeFirst()?.databaseValue ?? .null + return values.removeFirst() } } else { if values.isEmpty { throw DatabaseError(code: SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)", sql: statement.sql, arguments: nil) } else { - return values.removeFirst()?.databaseValue ?? .null + return values.removeFirst() } } } @@ -597,19 +597,9 @@ extension StatementArguments : ExpressibleByDictionaryLiteral { extension StatementArguments : CustomStringConvertible { /// A textual representation of `self`. public var description: String { - let valuesDescriptions = values.map { value -> String in - if let value = value { - return String(reflecting: value) - } else { - return "nil" - } - } + let valuesDescriptions = values.map { $0.description } let namedValuesDescriptions = namedValues.map { (key, value) -> String in - if let value = value { - return "\(key):\(String(reflecting: value))" - } else { - return "\(key):nil" - } + return "\(key):\(value))" } return "[" + (valuesDescriptions + namedValuesDescriptions).joined(separator: ", ") + "]" } diff --git a/GRDB/Core/Support/Foundation/NSData.swift b/GRDB/Core/Support/Foundation/NSData.swift index 427831b70..5c66dc344 100644 --- a/GRDB/Core/Support/Foundation/NSData.swift +++ b/GRDB/Core/Support/Foundation/NSData.swift @@ -11,9 +11,9 @@ extension NSData : DatabaseValueConvertible { /// Returns an NSData initialized from *databaseValue*, if it contains /// a Blob. public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? { - if let data = Data.fromDatabaseValue(databaseValue) { - return self.init(data: data) + guard let data = Data.fromDatabaseValue(databaseValue) else { + return nil } - return nil + return cast(data) } } diff --git a/GRDB/Core/Support/Foundation/NSDate.swift b/GRDB/Core/Support/Foundation/NSDate.swift index 4cb9913bc..783265b57 100644 --- a/GRDB/Core/Support/Foundation/NSDate.swift +++ b/GRDB/Core/Support/Foundation/NSDate.swift @@ -11,9 +11,9 @@ extension NSDate : DatabaseValueConvertible { /// Returns an NSDate initialized from *databaseValue*, if possible. public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? { - if let date = Date.fromDatabaseValue(databaseValue) { - return self.init(timeInterval: 0, since: date) + guard let date = Date.fromDatabaseValue(databaseValue) else { + return nil } - return nil + return cast(date) } } diff --git a/GRDB/Core/Support/Foundation/NSNull.swift b/GRDB/Core/Support/Foundation/NSNull.swift index e209faeb1..0e5d84d7c 100644 --- a/GRDB/Core/Support/Foundation/NSNull.swift +++ b/GRDB/Core/Support/Foundation/NSNull.swift @@ -1,7 +1,7 @@ import Foundation /// NSNull adopts DatabaseValueConvertible -extension NSNull: DatabaseValueConvertible { +extension NSNull : DatabaseValueConvertible { /// Returns DatabaseValue.null. public var databaseValue: DatabaseValue { diff --git a/GRDB/Core/Support/Foundation/NSNumber.swift b/GRDB/Core/Support/Foundation/NSNumber.swift index 4e6ebbf7a..448e56a3d 100644 --- a/GRDB/Core/Support/Foundation/NSNumber.swift +++ b/GRDB/Core/Support/Foundation/NSNumber.swift @@ -3,7 +3,7 @@ import Foundation private let integerRoundingBehavior = NSDecimalNumberHandler(roundingMode: .plain, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false) /// NSNumber adopts DatabaseValueConvertible -extension NSNumber: DatabaseValueConvertible { +extension NSNumber : DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { diff --git a/GRDB/Core/Support/Foundation/NSString.swift b/GRDB/Core/Support/Foundation/NSString.swift index 2b07f794b..782c77eb5 100644 --- a/GRDB/Core/Support/Foundation/NSString.swift +++ b/GRDB/Core/Support/Foundation/NSString.swift @@ -1,7 +1,7 @@ import Foundation /// NSString adopts DatabaseValueConvertible -extension NSString: DatabaseValueConvertible { +extension NSString : DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { diff --git a/GRDB/Core/Support/Foundation/NSURL.swift b/GRDB/Core/Support/Foundation/NSURL.swift index 23b2663ed..01745afb9 100644 --- a/GRDB/Core/Support/Foundation/NSURL.swift +++ b/GRDB/Core/Support/Foundation/NSURL.swift @@ -14,6 +14,6 @@ extension NSURL : DatabaseValueConvertible { guard let url = URL.fromDatabaseValue(databaseValue) else { return nil } - return self.init(string: url.absoluteString) + return cast(url) } } diff --git a/GRDB/Core/Support/Foundation/NSUUID.swift b/GRDB/Core/Support/Foundation/NSUUID.swift index dc69ac504..450bb6749 100644 --- a/GRDB/Core/Support/Foundation/NSUUID.swift +++ b/GRDB/Core/Support/Foundation/NSUUID.swift @@ -1,7 +1,7 @@ import Foundation /// NSUUID adopts DatabaseValueConvertible -extension NSUUID: DatabaseValueConvertible { +extension NSUUID : DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { diff --git a/GRDB/Core/Utils.swift b/GRDB/Core/Utils.swift index 540b983fc..2c70b4c32 100644 --- a/GRDB/Core/Utils.swift +++ b/GRDB/Core/Utils.swift @@ -55,6 +55,11 @@ func GRDBPrecondition(_ condition: @autoclosure() -> Bool, _ message: @autoclosu } } +// Workaround Swift inconvenience around factories methods of non-final classes +func cast(_ value: T) -> U? { + return value as? U +} + extension Array { /// Removes the first object that matches *predicate*. mutating func removeFirst(_ predicate: (Element) throws -> Bool) rethrows { diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index d1de89e9a..cf5084ae0 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -2,33 +2,33 @@ /// /// See https://github.com/groue/GRDB.swift#the-query-interface public struct QueryInterfaceRequest { - let query: _SQLSelectQuery + let query: QueryInterfaceSelectQueryDefinition /// Initializes a QueryInterfaceRequest based on table *tableName*. /// /// It represents the SQL query `SELECT * FROM tableName`. public init(tableName: String) { - self.init(query: _SQLSelectQuery(select: [_SQLResultColumn.star(nil)], from: .table(name: tableName, alias: nil))) + self.init(query: QueryInterfaceSelectQueryDefinition(select: [star], from: .table(name: tableName, alias: nil))) } - init(query: _SQLSelectQuery) { + init(query: QueryInterfaceSelectQueryDefinition) { self.query = query } } -extension QueryInterfaceRequest : FetchRequest { +extension QueryInterfaceRequest : SQLSelectQuery { - /// Returns a prepared statement that is ready to be executed. + /// This function is an implementation detail of the query interface. + /// Do not use it directly. /// - /// - throws: A DatabaseError whenever SQLite could not parse the sql query. - public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - // TODO: split statement generation from arguments building - var arguments: StatementArguments? = StatementArguments() - let sql = query.sql(&arguments) - let statement = try db.makeSelectStatement(sql) - try statement.setArgumentsWithValidation(arguments!) - return (statement, nil) + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// See SQLSelectQuery.selectQuerySQL(_) + public func selectQuerySQL(_ arguments: inout StatementArguments?) -> String { + return query.selectQuerySQL(&arguments) } } @@ -87,12 +87,12 @@ extension QueryInterfaceRequest { // MARK: Request Derivation /// Returns a new QueryInterfaceRequest with a new net of selected columns. - public func select(_ selection: _SQLSelectable...) -> QueryInterfaceRequest { + public func select(_ selection: SQLSelectable...) -> QueryInterfaceRequest { return select(selection) } /// Returns a new QueryInterfaceRequest with a new net of selected columns. - public func select(_ selection: [_SQLSelectable]) -> QueryInterfaceRequest { + public func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest { var query = self.query query.selection = selection return QueryInterfaceRequest(query: query) @@ -100,7 +100,7 @@ extension QueryInterfaceRequest { /// Returns a new QueryInterfaceRequest with a new net of selected columns. public func select(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { - return select(_SQLExpression.sqlLiteral(sql, arguments)) + return select(SQLExpressionLiteral(sql, arguments: arguments)) } /// Returns a new QueryInterfaceRequest which returns distinct rows. @@ -115,7 +115,7 @@ extension QueryInterfaceRequest { public func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest { var query = self.query if let whereExpression = query.whereExpression { - query.whereExpression = .infixOperator("AND", whereExpression, predicate.sqlExpression) + query.whereExpression = whereExpression && predicate.sqlExpression } else { query.whereExpression = predicate.sqlExpression } @@ -125,7 +125,7 @@ extension QueryInterfaceRequest { /// Returns a new QueryInterfaceRequest with the provided *predicate* added to the /// eventual set of already applied predicates. public func filter(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { - return filter(_SQLExpression.sqlLiteral(sql, arguments)) + return filter(SQLExpressionLiteral(sql, arguments: arguments)) } /// Returns a new QueryInterfaceRequest grouped according to *expressions*. @@ -142,7 +142,7 @@ extension QueryInterfaceRequest { /// Returns a new QueryInterfaceRequest with a new grouping. public func group(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { - return group(_SQLExpression.sqlLiteral(sql, arguments)) + return group(SQLExpressionLiteral(sql, arguments: arguments)) } /// Returns a new QueryInterfaceRequest with the provided *predicate* added to the @@ -160,18 +160,18 @@ extension QueryInterfaceRequest { /// Returns a new QueryInterfaceRequest with the provided *sql* added to /// the eventual set of already applied predicates. public func having(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { - return having(_SQLExpression.sqlLiteral(sql, arguments)) + return having(SQLExpressionLiteral(sql, arguments: arguments)) } /// Returns a new QueryInterfaceRequest with the provided *orderings* added to /// the eventual set of already applied orderings. - public func order(_ orderings: _SQLOrderable...) -> QueryInterfaceRequest { + public func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest { return order(orderings) } /// Returns a new QueryInterfaceRequest with the provided *orderings* added to /// the eventual set of already applied orderings. - public func order(_ orderings: [_SQLOrderable]) -> QueryInterfaceRequest { + public func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest { var query = self.query query.orderings = orderings return QueryInterfaceRequest(query: query) @@ -180,7 +180,7 @@ extension QueryInterfaceRequest { /// Returns a new QueryInterfaceRequest with the provided *sql* added to the /// eventual set of already applied orderings. public func order(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { - return order([_SQLExpression.sqlLiteral(sql, arguments)]) + return order([SQLExpressionLiteral(sql, arguments: arguments)]) } /// Returns a new QueryInterfaceRequest sorted in reversed order. @@ -194,7 +194,7 @@ extension QueryInterfaceRequest { /// *offset*. public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { var query = self.query - query.limit = _SQLLimit(limit: limit, offset: offset) + query.limit = SQLLimit(limit: limit, offset: offset) return QueryInterfaceRequest(query: query) } } @@ -208,7 +208,7 @@ extension QueryInterfaceRequest { /// /// - parameter db: A database connection. public func fetchCount(_ db: Database) -> Int { - return Int.fetchOne(db, QueryInterfaceRequest(query: query.countQuery))! + return Int.fetchOne(db, query.countRequest)! } } @@ -229,24 +229,6 @@ extension QueryInterfaceRequest { } -extension QueryInterfaceRequest { - - // MARK: QueryInterfaceRequest as subquery - - /// Returns an SQL expression that checks the inclusion of a value in - /// the results of another request. - public func contains(_ element: SQLExpressible) -> _SQLExpression { - return .inSubQuery(query, element.sqlExpression) - } - - /// Returns an SQL expression that checks whether the receiver, as a - /// subquery, returns any row. - public func exists() -> _SQLExpression { - return .exists(query) - } -} - - extension TableMapping { // MARK: Request Derivation @@ -257,12 +239,12 @@ extension TableMapping { } /// Returns a QueryInterfaceRequest which selects *selection*. - public static func select(_ selection: _SQLSelectable...) -> QueryInterfaceRequest { + public static func select(_ selection: SQLSelectable...) -> QueryInterfaceRequest { return all().select(selection) } /// Returns a QueryInterfaceRequest which selects *selection*. - public static func select(_ selection: [_SQLSelectable]) -> QueryInterfaceRequest { + public static func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest { return all().select(selection) } @@ -283,13 +265,13 @@ extension TableMapping { /// Returns a QueryInterfaceRequest sorted according to the /// provided *orderings*. - public static func order(_ orderings: _SQLOrderable...) -> QueryInterfaceRequest { + public static func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest { return all().order(orderings) } /// Returns a QueryInterfaceRequest sorted according to the /// provided *orderings*. - public static func order(_ orderings: [_SQLOrderable]) -> QueryInterfaceRequest { + public static func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest { return all().order(orderings) } diff --git a/GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift b/GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift new file mode 100644 index 000000000..623e1dc14 --- /dev/null +++ b/GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift @@ -0,0 +1,228 @@ +#if !USING_BUILTIN_SQLITE + #if os(OSX) + import SQLiteMacOSX + #elseif os(iOS) + #if (arch(i386) || arch(x86_64)) + import SQLiteiPhoneSimulator + #else + import SQLiteiPhoneOS + #endif + #elseif os(watchOS) + #if (arch(i386) || arch(x86_64)) + import SQLiteWatchSimulator + #else + import SQLiteWatchOS + #endif + #endif +#endif + + +// MARK: - QueryInterfaceSelectQueryDefinition + +struct QueryInterfaceSelectQueryDefinition { + var selection: [SQLSelectable] + var isDistinct: Bool + var source: SQLSource? + var whereExpression: SQLExpression? + var groupByExpressions: [SQLExpression] + var orderings: [SQLOrderingTerm] + var isReversed: Bool + var havingExpression: SQLExpression? + var limit: SQLLimit? + + init( + select selection: [SQLSelectable], + isDistinct: Bool = false, + from source: SQLSource? = nil, + filter whereExpression: SQLExpression? = nil, + groupBy groupByExpressions: [SQLExpression] = [], + orderBy orderings: [SQLOrderingTerm] = [], + isReversed: Bool = false, + having havingExpression: SQLExpression? = nil, + limit: SQLLimit? = nil) + { + self.selection = selection + self.isDistinct = isDistinct + self.source = source + self.whereExpression = whereExpression + self.groupByExpressions = groupByExpressions + self.orderings = orderings + self.isReversed = isReversed + self.havingExpression = havingExpression + self.limit = limit + } + + func sql(_ arguments: inout StatementArguments?) -> String { + var sql = "SELECT" + + if isDistinct { + sql += " DISTINCT" + } + + assert(!selection.isEmpty) + sql += " " + selection.map { $0.resultColumnSQL(&arguments) }.joined(separator: ", ") + + if let source = source { + sql += " FROM " + source.sourceSQL(&arguments) + } + + if let whereExpression = whereExpression { + sql += " WHERE " + whereExpression.expressionSQL(&arguments) + } + + if !groupByExpressions.isEmpty { + sql += " GROUP BY " + groupByExpressions.map { $0.expressionSQL(&arguments) }.joined(separator: ", ") + } + + if let havingExpression = havingExpression { + sql += " HAVING " + havingExpression.expressionSQL(&arguments) + } + + var orderings = self.orderings + if isReversed { + if orderings.isEmpty { + // https://www.sqlite.org/lang_createtable.html#rowid + // + // > The rowid value can be accessed using one of the special + // > case-independent names "rowid", "oid", or "_rowid_" in + // > place of a column name. If a table contains a user defined + // > column named "rowid", "oid" or "_rowid_", then that name + // > always refers the explicitly declared column and cannot be + // > used to retrieve the integer rowid value. + // + // Here we assume that _rowid_ is not a custom column. + // TODO: support for user-defined _rowid_ column. + // TODO: support for WITHOUT ROWID tables. + orderings = [Column("_rowid_").desc] + } else { + orderings = orderings.map { $0.reversed } + } + } + if !orderings.isEmpty { + sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ") + } + + if let limit = limit { + sql += " LIMIT " + limit.sql + } + + return sql + } + + /// Returns a fetch request that counts the number of rows matched by self. + var countRequest: FetchRequest { + guard groupByExpressions.isEmpty && limit == nil else { + // SELECT ... GROUP BY ... + // SELECT ... LIMIT ... + return trivialCountQuery + } + + guard let source = source, case .table(name: let tableName, alias: let alias) = source else { + // SELECT ... FROM (something which is not a table) + return trivialCountQuery + } + + assert(!selection.isEmpty) + if selection.count == 1 { + guard let selectable = self.selection[0].countingSelectable(distinct: isDistinct, from: tableName, aliased: alias) else { + return trivialCountQuery + } + var countQuery = unorderedQuery + countQuery.isDistinct = false + countQuery.selection = [selectable] + return countQuery + } else { + // SELECT [DISTINCT] expr1, expr2, ... FROM tableName ... + + guard !isDistinct else { + return trivialCountQuery + } + + // SELECT expr1, expr2, ... FROM tableName ... + // -> + // SELECT COUNT(*) FROM tableName ... + var countQuery = unorderedQuery + countQuery.selection = [SQLExpressionCount(star)] + return countQuery + } + } + + func makeDeleteStatement(_ db: Database) -> UpdateStatement { + guard groupByExpressions.isEmpty else { + fatalError("Can't delete query with GROUP BY expression") + } + + guard havingExpression == nil else { + fatalError("Can't delete query with GROUP BY expression") + } + + guard limit == nil else { + fatalError("Can't delete query with limit") + } + + var sql = "DELETE" + var arguments: StatementArguments? = StatementArguments() + + if let source = source { + sql += " FROM " + source.sourceSQL(&arguments) + } + + if let whereExpression = whereExpression { + sql += " WHERE " + whereExpression.expressionSQL(&arguments) + } + + let statement = try! db.makeUpdateStatement(sql) + statement.arguments = arguments! + return statement + } + + // SELECT COUNT(*) FROM (self) + private var trivialCountQuery: QueryInterfaceSelectQueryDefinition { + return QueryInterfaceSelectQueryDefinition( + select: [SQLExpressionCount(star)], + from: .query(query: unorderedQuery, alias: nil)) + } + + /// Remove ordering + private var unorderedQuery: QueryInterfaceSelectQueryDefinition { + var query = self + query.isReversed = false + query.orderings = [] + return query + } +} + +indirect enum SQLSource { + case table(name: String, alias: String?) + case query(query: QueryInterfaceSelectQueryDefinition, alias: String?) + + func sourceSQL(_ arguments: inout StatementArguments?) -> String { + switch self { + case .table(let table, let alias): + if let alias = alias { + return table.quotedDatabaseIdentifier + " AS " + alias.quotedDatabaseIdentifier + } else { + return table.quotedDatabaseIdentifier + } + case .query(let query, let alias): + if let alias = alias { + return "(" + query.sql(&arguments) + ") AS " + alias.quotedDatabaseIdentifier + } else { + return "(" + query.sql(&arguments) + ")" + } + } + } +} + +struct SQLLimit { + let limit: Int + let offset: Int? + + var sql: String { + if let offset = offset { + return "\(limit) OFFSET \(offset)" + } else { + return "\(limit)" + } + } +} diff --git a/GRDB/QueryInterface/SQLCollatedExpression.swift b/GRDB/QueryInterface/SQLCollatedExpression.swift new file mode 100644 index 000000000..fcc588522 --- /dev/null +++ b/GRDB/QueryInterface/SQLCollatedExpression.swift @@ -0,0 +1,49 @@ +/// SQLCollatedExpression taints an expression so that every derived expression +/// is eventually evaluated using an SQLite collation. +/// +/// You create one by calling the SQLSpecificExpressible.collating() method. +/// +/// let email: SQLCollatedExpression = Column("email").collating(.nocase) +/// +/// // SELECT * FROM persons WHERE email = 'arthur@example.com' COLLATE NOCASE +/// Persons.filter(email == "arthur@example.com") +public struct SQLCollatedExpression { + /// The tainted expression + public let expression: SQLExpression + + /// The name of the collation + public let collationName: Database.CollationName + + /// Returns an ordering suitable for QueryInterfaceRequest.order() + /// + /// let email: SQLCollatedExpression = Column("email").collating(.nocase) + /// + /// // SELECT * FROM persons ORDER BY email COLLATE NOCASE ASC + /// Persons.order(email.asc) + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + public var asc: SQLOrderingTerm { + return SQLOrdering.asc(sqlExpression) + } + + /// Returns an ordering suitable for QueryInterfaceRequest.order() + /// + /// let email: SQLCollatedExpression = Column("email").collating(.nocase) + /// + /// // SELECT * FROM persons ORDER BY email COLLATE NOCASE DESC + /// Persons.order(email.desc) + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + public var desc: SQLOrderingTerm { + return SQLOrdering.desc(sqlExpression) + } + + init(_ expression: SQLExpression, collationName: Database.CollationName) { + self.expression = expression + self.collationName = collationName + } + + var sqlExpression: SQLExpression { + return SQLExpressionCollate(expression, collationName: collationName) + } +} diff --git a/GRDB/QueryInterface/SQLCollation.swift b/GRDB/QueryInterface/SQLCollation.swift deleted file mode 100644 index 59c135201..000000000 --- a/GRDB/QueryInterface/SQLCollation.swift +++ /dev/null @@ -1,247 +0,0 @@ -/// This protocol is an implementation detail of the query interface. -/// Do not use it directly. -/// -/// See https://github.com/groue/GRDB.swift/#the-query-interface -public struct _SQLCollatedExpression { - let baseExpression: _SQLExpression - let collationName: String -} - -extension _SQLCollatedExpression : SQLExpressible { - - /// This property is an implementation detail of the query interface. - /// Do not use it directly. - /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface - public var sqlExpression: _SQLExpression { - return .collate(baseExpression, collationName) - } -} - -extension _SQLCollatedExpression : _SQLOrderable { - - /// This property is an implementation detail of the query interface. - /// Do not use it directly. - /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface - public var reversedOrdering: _SQLOrderingExpression { - return .desc(sqlExpression) - } - - /// Returns a value that can be used as an argument to FetchRequest.order() - /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface - public var asc: _SQLOrderingExpression { - return .asc(sqlExpression) - } - - /// Returns a value that can be used as an argument to FetchRequest.order() - /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface - public var desc: _SQLOrderingExpression { - return .desc(sqlExpression) - } - - /// This method is an implementation detail of the query interface. - /// Do not use it directly. - /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface - public func orderingSQL(_ arguments: inout StatementArguments?) -> String { - return sqlExpression.orderingSQL(&arguments) - } -} - -extension _SpecificSQLExpressible { - - public func collating(_ collationName: String) -> _SQLCollatedExpression { - return _SQLCollatedExpression(baseExpression: sqlExpression, collationName: collationName) - } - - /// This method is an implementation detail of the query interface. - /// Do not use it directly. - /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface - public func collating(_ collation: SQLCollation) -> _SQLCollatedExpression { - return collating(collation.rawValue) - } - - /// This method is an implementation detail of the query interface. - /// Do not use it directly. - /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface - public func collating(_ collation: DatabaseCollation) -> _SQLCollatedExpression { - return collating(collation.name) - } -} - - -// MARK: - Operator = COLLATE - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func == (lhs: _SQLCollatedExpression, rhs: SQLExpressible?) -> _SQLExpression { - return .collate(lhs.baseExpression == rhs, lhs.collationName) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func == (lhs: SQLExpressible?, rhs: _SQLCollatedExpression) -> _SQLExpression { - return .collate(lhs == rhs.baseExpression, rhs.collationName) -} - - -// MARK: - Operator != COLLATE - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func != (lhs: _SQLCollatedExpression, rhs: SQLExpressible?) -> _SQLExpression { - return .collate(lhs.baseExpression != rhs, lhs.collationName) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func != (lhs: SQLExpressible?, rhs: _SQLCollatedExpression) -> _SQLExpression { - return .collate(lhs != rhs.baseExpression, rhs.collationName) -} - - -// MARK: - Operator < COLLATE - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func < (lhs: _SQLCollatedExpression, rhs: SQLExpressible) -> _SQLExpression { - return .collate(lhs.baseExpression < rhs, lhs.collationName) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func < (lhs: SQLExpressible, rhs: _SQLCollatedExpression) -> _SQLExpression { - return .collate(lhs < rhs.baseExpression, rhs.collationName) -} - - -// MARK: - Operator <= COLLATE - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func <= (lhs: _SQLCollatedExpression, rhs: SQLExpressible) -> _SQLExpression { - return .collate(lhs.baseExpression <= rhs, lhs.collationName) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func <= (lhs: SQLExpressible, rhs: _SQLCollatedExpression) -> _SQLExpression { - return .collate(lhs <= rhs.baseExpression, rhs.collationName) -} - - -// MARK: - Operator > COLLATE - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func > (lhs: _SQLCollatedExpression, rhs: SQLExpressible) -> _SQLExpression { - return .collate(lhs.baseExpression > rhs, lhs.collationName) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func > (lhs: SQLExpressible, rhs: _SQLCollatedExpression) -> _SQLExpression { - return .collate(lhs > rhs.baseExpression, rhs.collationName) -} - - -// MARK: - Operator >= COLLATE - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func >= (lhs: _SQLCollatedExpression, rhs: SQLExpressible) -> _SQLExpression { - return .collate(lhs.baseExpression >= rhs, lhs.collationName) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func >= (lhs: SQLExpressible, rhs: _SQLCollatedExpression) -> _SQLExpression { - return .collate(lhs >= rhs.baseExpression, rhs.collationName) -} - - -// MARK: - Operator BETWEEN COLLATE - -extension Range where Bound: SQLExpressible { - /// Returns an SQL expression that compares the inclusion of a value in - /// a range. - /// - /// See https://github.com/groue/GRDB.swift/#sql-operators - public func contains(_ element: _SQLCollatedExpression) -> _SQLExpression { - return (element >= lowerBound) && (element < upperBound) - } -} - -extension ClosedRange where Bound: SQLExpressible { - /// Returns an SQL expression that compares the inclusion of a value in - /// a range. - /// - /// See https://github.com/groue/GRDB.swift/#sql-operators - public func contains(_ element: _SQLCollatedExpression) -> _SQLExpression { - return .collate(contains(element.baseExpression), element.collationName) - } -} - - -// MARK: - Operator IN COLLATE - -extension Sequence where Self.Iterator.Element: SQLExpressible { - /// Returns an SQL expression that compares the inclusion of a value in - /// a sequence. - /// - /// See https://github.com/groue/GRDB.swift/#sql-operators - public func contains(_ element: _SQLCollatedExpression) -> _SQLExpression { - return .collate(contains(element.baseExpression), element.collationName) - } -} - - -// MARK: - Operator IS COLLATE - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func === (lhs: _SQLCollatedExpression, rhs: SQLExpressible?) -> _SQLExpression { - return .collate(lhs.baseExpression === rhs, lhs.collationName) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func === (lhs: SQLExpressible?, rhs: _SQLCollatedExpression) -> _SQLExpression { - return .collate(lhs == rhs.baseExpression, rhs.collationName) -} - - -// MARK: - Operator IS NOT COLLATE - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func !== (lhs: _SQLCollatedExpression, rhs: SQLExpressible?) -> _SQLExpression { - return .collate(lhs.baseExpression !== rhs, lhs.collationName) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func !== (lhs: SQLExpressible?, rhs: _SQLCollatedExpression) -> _SQLExpression { - return .collate(lhs !== rhs.baseExpression, rhs.collationName) -} diff --git a/GRDB/QueryInterface/SQLCollection.swift b/GRDB/QueryInterface/SQLCollection.swift new file mode 100644 index 000000000..f125193dd --- /dev/null +++ b/GRDB/QueryInterface/SQLCollection.swift @@ -0,0 +1,85 @@ +// MARK: - SQLCollection + +/// This protocol is an implementation detail of the query interface. +/// Do not use it directly. +/// +/// See https://github.com/groue/GRDB.swift/#the-query-interface +/// +/// # Low Level Query Interface +/// +/// SQLCollection is the protocol for types that can be checked for inclusion. +public protocol SQLCollection { + /// This function is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// Returns an SQL string that represents the collection. + /// + /// When the arguments parameter is nil, any value must be written down as + /// a literal in the returned SQL: + /// + /// var arguments: StatementArguments? = nil + /// let collection = SQLExpressionsArray([1,2,3]) + /// collection.collectionSQL(&arguments) // "1,2,3" + /// + /// When the arguments parameter is not nil, then values may be replaced by + /// `?` or colon-prefixed tokens, and fed into arguments. + /// + /// var arguments = StatementArguments() + /// let collection = SQLExpressionsArray([1,2,3]) + /// collection.collectionSQL(&arguments) // "?,?,?" + /// arguments // [1,2,3] + func collectionSQL(_ arguments: inout StatementArguments?) -> String + + /// Returns an expression that check whether the collection contains + /// the expression. + /// + /// The default implementation returns a SQLExpressionContains which applies + /// the `IN` operator: + /// + /// let request = Person.select(Column("id")) + /// request.contains(Column("id")) // id IN (SELECT id FROM persons) + func contains(_ value: SQLExpressible) -> SQLExpression +} + + +// MARK: Default Implementations + +extension SQLCollection { + /// Returns a SQLExpressionContains which applies the `IN` operator: + /// + /// let request = Person.select(Column("id")) + /// request.contains(Column("id")) // id IN (SELECT id FROM persons) + public func contains(_ value: SQLExpressible) -> SQLExpression { + return SQLExpressionContains(value, self) + } +} + + +// MARK: - SQLExpressionsArray + +/// SQLExpressionsArray wraps an array of expressions +/// +/// SQLExpressionsArray([1, 2, 3]) +struct SQLExpressionsArray : SQLCollection { + let expressions: [SQLExpression] + + init(_ expressions: S) where S.Iterator.Element : SQLExpressible { + self.expressions = expressions.map { $0.sqlExpression } + } + + func collectionSQL(_ arguments: inout StatementArguments?) -> String { + return (expressions.map { $0.expressionSQL(&arguments) } as [String]).joined(separator: ", ") + } + + func contains(_ value: SQLExpressible) -> SQLExpression { + if expressions.isEmpty { + return false.databaseValue + } else { + return SQLExpressionContains(value, self) + } + } +} diff --git a/GRDB/QueryInterface/SQLExpression.swift b/GRDB/QueryInterface/SQLExpression.swift new file mode 100644 index 000000000..7716dd045 --- /dev/null +++ b/GRDB/QueryInterface/SQLExpression.swift @@ -0,0 +1,733 @@ +// MARK: - SQLExpression + +/// This protocol is an implementation detail of the query interface. +/// Do not use it directly. +/// +/// See https://github.com/groue/GRDB.swift/#the-query-interface +/// +/// # Low Level Query Interface +/// +/// SQLExpression is the protocol for types that represent an SQL expression, as +/// described at https://www.sqlite.org/lang_expr.html +/// +/// GRDB ships with a variety of types that already adopt this protocol, and +/// allow to represent many SQLite expressions: +/// +/// - Column +/// - DatabaseValue +/// - SQLExpressionLiteral +/// - SQLExpressionUnary +/// - SQLExpressionBinary +/// - SQLExpressionExists +/// - SQLExpressionFunction +/// - SQLExpressionCollate +public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderingTerm { + + /// This function is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// Returns an SQL string that represents the expression. + /// + /// When the arguments parameter is nil, any value must be written down as + /// a literal in the returned SQL: + /// + /// var arguments: StatementArguments? = nil + /// let expression = "foo'bar".databaseValue + /// expression.expressionSQL(&arguments) // "'foo''bar'" + /// + /// When the arguments parameter is not nil, then values may be replaced by + /// `?` or colon-prefixed tokens, and fed into arguments. + /// + /// var arguments = StatementArguments() + /// let expression = "foo'bar".databaseValue + /// expression.expressionSQL(&arguments) // "?" + /// arguments // ["foo'bar"] + func expressionSQL(_ arguments: inout StatementArguments?) -> String + + /// This property is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// Returns the expression, negated. This property fuels the `!` operator. + /// + /// The default implementation returns the expression prefixed by `NOT`. + /// + /// let column = Column("favorite") + /// column.negated // NOT favorite + /// + /// Some expressions may provide a custom implementation that returns a + /// more natural SQL expression. + /// + /// let expression = [1,2,3].contains(Column("id")) // id IN (1,2,3) + /// expression.negated // id NOT IN (1,2,3) + var negated: SQLExpression { get } +} + +// MARK: Default Implementations + +extension SQLExpression { + + /// This property is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// The default implementation returns the expression prefixed by `NOT`. + /// + /// let column = Column("favorite") + /// column.negated // NOT favorite + /// + public var negated: SQLExpression { + return SQLExpressionUnary(.not, self) + } + + /// This property is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// Converts an expression to an SQLExpressionLiteral + public var literal: SQLExpressionLiteral { + var arguments: StatementArguments? = [] + let sql = expressionSQL(&arguments) + return SQLExpressionLiteral(sql, arguments: arguments) + } + + /// The expression as a quoted SQL literal (not public in order to avoid abuses) + /// + /// "foo'bar".databaseValue.sql // "'foo''bar'"" + var sql: String { + var arguments: StatementArguments? = nil + return expressionSQL(&arguments) + } +} + +// MARK: SQLExpressible Adoption + +extension SQLExpression { + + /// This property is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// See SQLExpressible.sqlExpression + public var sqlExpression: SQLExpression { + return self + } +} + +// MARK: SQLSelectable Adoption + +extension SQLExpression { + + /// This function is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// See SQLSelectable.countingSelectable(distinct:from:aliased:) + public func countingSelectable(distinct: Bool, from tableName: String, aliased alias: String?) -> SQLSelectable? { + if distinct { + // SELECT DISTINCT expr FROM tableName ... + // -> + // SELECT COUNT(DISTINCT expr) FROM tableName ... + return SQLExpressionCountDistinct(self) + } else { + // SELECT expr FROM tableName ... + // -> + // SELECT COUNT(*) FROM tableName ... + return SQLExpressionCount(star) + } + } +} + + +// MARK: - Column + +/// A column in the database +/// +/// See https://github.com/groue/GRDB.swift#the-query-interface +public struct Column { + /// The name of the column + public let name: String + + /// Creates a column given its name. + public init(_ name: String) { + self.name = name + } +} + +extension Column : SQLExpression { + + /// This function is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// See SQLExpression.expressionSQL(_:arguments:) + public func expressionSQL(_ arguments: inout StatementArguments?) -> String { + return name.quotedDatabaseIdentifier + } +} + + +// MARK: - DatabaseValue + +extension DatabaseValue : SQLExpression { + /// This function is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// See SQLExpression.expressionSQL(_:arguments:) + public func expressionSQL(_ arguments: inout StatementArguments?) -> String { + // fast path for NULL + if isNull { + return "NULL" + } + + if arguments != nil { + arguments!.values.append(self) + return "?" + } else { + // Slow but reliable implementation. + return DatabaseValue.quotingConnection.inDatabase { String.fetchOne($0, "SELECT QUOTE(?)", arguments: [self])! } + } + } + + // Support for DatabaseValue.expressionSQL(&nil) + private static let quotingConnection: DatabaseQueue = DatabaseQueue() +} + + +// MARK: - SQLExpressionLiteral + +/// This type is an implementation detail of the query interface. +/// Do not use it directly. +/// +/// See https://github.com/groue/GRDB.swift/#the-query-interface +/// +/// # Low Level Query Interface +/// +/// SQLExpressionLiteral is an expression built from a raw SQL snippet. +/// +/// SQLExpressionLiteral("1 + 2") +/// +/// The SQL literal may contain `?` and colon-prefixed tokens: +/// +/// SQLExpressionLiteral("? + ?", arguments: [1, 2]) +/// SQLExpressionLiteral(":one + :two", arguments: ["one": 1, "two": 2]) +public struct SQLExpressionLiteral : SQLExpression { + /// The SQL literal + public let sql: String + + /// Eventual arguments that feed the `?` and colon-prefixed tokens in the + /// SQL literal + public let arguments: StatementArguments? + + /// Creates an SQL literal expression. + /// + /// SQLExpressionLiteral("1 + 2") + /// SQLExpressionLiteral("? + ?", arguments: [1, 2]) + /// SQLExpressionLiteral(":one + :two", arguments: ["one": 1, "two": 2]) + public init(_ sql: String, arguments: StatementArguments? = nil) { + self.sql = sql + self.arguments = arguments + } + + /// This function is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// See SQLExpression.expressionSQL(_:arguments:) + public func expressionSQL(_ arguments: inout StatementArguments?) -> String { + if let literalArguments = self.arguments { + guard arguments != nil else { + fatalError("Not implemented") + } + arguments!.values.append(contentsOf: literalArguments.values) + for (name, value) in literalArguments.namedValues { + guard arguments!.namedValues[name] == nil else { + fatalError("argument \(String(reflecting: name)) can't be reused") + } + arguments!.namedValues[name] = value + } + } + return sql + } +} + + +// MARK: - SQLExpressionUnary + +/// This type is an implementation detail of the query interface. +/// Do not use it directly. +/// +/// See https://github.com/groue/GRDB.swift/#the-query-interface +/// +/// # Low Level Query Interface +/// +/// SQLUnaryOperator is a SQLite unary operator. +public struct SQLUnaryOperator : Hashable { + /// The SQL operator + public let sql: String + + /// If true GRDB puts a white space between the operator and the operand. + public let needsRightSpace: Bool + + /// Creates an unary operator + /// + /// SQLUnaryOperator("~", needsRightSpace: false) + public init(_ sql: String, needsRightSpace: Bool) { + self.sql = sql + self.needsRightSpace = needsRightSpace + } + + public var hashValue: Int { + return sql.hashValue + } +} + +public func ==(lhs: SQLUnaryOperator, rhs: SQLUnaryOperator) -> Bool { + return lhs.sql == rhs.sql +} + +/// This type is an implementation detail of the query interface. +/// Do not use it directly. +/// +/// See https://github.com/groue/GRDB.swift/#the-query-interface +/// +/// # Low Level Query Interface +/// +/// SQLExpressionUnary is an expression made of an unary operator and +/// an operand expression. +/// +/// SQLExpressionUnary(.not, Column("favorite")) +public struct SQLExpressionUnary : SQLExpression { + /// The unary operator + public let op: SQLUnaryOperator + + /// The operand + public let expression: SQLExpression + + /// Creates an expression made of an unary operator and + /// an operand expression. + /// + /// // NOT favorite + /// SQLExpressionUnary(.not, Column("favorite")) + public init(_ op: SQLUnaryOperator, _ value: SQLExpressible) { + self.op = op + self.expression = value.sqlExpression + } + + /// This function is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// See SQLExpression.expressionSQL(_:arguments:) + public func expressionSQL(_ arguments: inout StatementArguments?) -> String { + return op.sql + (op.needsRightSpace ? " " : "") + expression.expressionSQL(&arguments) + } +} + + +// MARK: - SQLExpressionBinary + +/// This type is an implementation detail of the query interface. +/// Do not use it directly. +/// +/// See https://github.com/groue/GRDB.swift/#the-query-interface +/// +/// # Low Level Query Interface +/// +/// SQLBinaryOperator is a SQLite binary operator. +public struct SQLBinaryOperator : Hashable { + /// The SQL operator + public let sql: String + + /// The SQL for the negated operator, if any + public let negatedSQL: String? + + /// Creates a binary operator + /// + /// SQLBinaryOperator("+") + /// SQLBinaryOperator("IS", negated: "IS NOT") + public init(_ sql: String, negated: String? = nil) { + self.sql = sql + self.negatedSQL = negated + } + + public var hashValue: Int { + return sql.hashValue + } + + /// Returns the negated binary operator, if any + /// + /// let operator = SQLBinaryOperator("IS", negated: "IS NOT") + /// operator.negated!.sql // IS NOT + public var negated: SQLBinaryOperator? { + guard let negatedSQL = negatedSQL else { + return nil + } + return SQLBinaryOperator(negatedSQL, negated: sql) + } +} + +public func ==(lhs: SQLBinaryOperator, rhs: SQLBinaryOperator) -> Bool { + return lhs.sql == rhs.sql +} + +/// This type is an implementation detail of the query interface. +/// Do not use it directly. +/// +/// See https://github.com/groue/GRDB.swift/#the-query-interface +/// +/// # Low Level Query Interface +/// +/// SQLExpressionBinary is an expression made of two expressions joined with a +/// binary operator. +/// +/// SQLExpressionBinary(.multiply, Column("length"), Column("width")) +public struct SQLExpressionBinary : SQLExpression { + /// The left operand + public let lhs: SQLExpression + + /// The operator + public let op: SQLBinaryOperator + + /// The right operand + public let rhs: SQLExpression + + /// Creates an expression made of two expressions joined with a + /// binary operator. + /// + /// // length * width + /// SQLExpressionBinary(.multiply, Column("length"), Column("width")) + public init(_ op: SQLBinaryOperator, _ lhs: SQLExpressible, _ rhs: SQLExpressible) { + self.lhs = lhs.sqlExpression + self.op = op + self.rhs = rhs.sqlExpression + } + + /// This function is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// See SQLExpression.expressionSQL(_:arguments:) + public func expressionSQL(_ arguments: inout StatementArguments?) -> String { + return "(" + lhs.expressionSQL(&arguments) + " " + op.sql + " " + rhs.expressionSQL(&arguments) + ")" + } + + /// This property is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// See SQLExpression.negated + public var negated: SQLExpression { + if let negatedOp = op.negated { + return SQLExpressionBinary(negatedOp, lhs, rhs) + } else { + return SQLExpressionUnary(.not, self) + } + } +} + + +// MARK: - SQLExpressionContains + +/// SQLExpressionContains is an expression that checks the inclusion of a +/// value in a collection with the `IN` operator. +/// +/// // id IN (1,2,3) +/// SQLExpressionContains(Column("id"), SQLExpressionsArray([1,2,3])) +struct SQLExpressionContains : SQLExpression { + let expression: SQLExpression + let collection: SQLCollection + let isNegated: Bool + + init(_ value: SQLExpressible, _ collection: SQLCollection, negated: Bool = false) { + self.expression = value.sqlExpression + self.collection = collection + self.isNegated = negated + } + + func expressionSQL(_ arguments: inout StatementArguments?) -> String { + return "(" + + expression.expressionSQL(&arguments) + + (isNegated ? " NOT IN (" : " IN (") + + collection.collectionSQL(&arguments) + + "))" + } + + var negated: SQLExpression { + return SQLExpressionContains(expression, collection, negated: !isNegated) + } +} + + +// MARK: - SQLExpressionExists + +/// This type is an implementation detail of the query interface. +/// Do not use it directly. +/// +/// See https://github.com/groue/GRDB.swift/#the-query-interface +/// +/// # Low Level Query Interface +/// +/// SQLExpressionExists is an expression that checks if a subquery would return +/// rows or not with the `EXISTS` operator. +public struct SQLExpressionExists : SQLExpression { + /// The query + public let query: SQLSelectQuery + + /// If true, uses `NOT EXISTS` instead of `EXISTS` operator + public let isNegated: Bool + + /// Creates an expression that checks if a subquery would return rows + /// or not with the `EXISTS` operator. + public init(_ query: SQLSelectQuery, negated: Bool = false) { + self.query = query + self.isNegated = negated + } + + /// This function is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// See SQLExpression.expressionSQL(_:arguments:) + public func expressionSQL(_ arguments: inout StatementArguments?) -> String { + return "(" + + (isNegated ? "NOT EXISTS (" : "EXISTS (") + + query.selectQuerySQL(&arguments) + + "))" + } + + /// This property is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// See SQLExpression.negated + public var negated: SQLExpression { + return SQLExpressionExists(query, negated: !isNegated) + } +} + + +// MARK: - SQLExpressionBetween + +/// SQLExpressionBetween is an expression that checks if a values is included +/// in a range with the `BETWEEN` operator. +/// +/// // id BETWEEN 1 AND 3 +/// SQLExpressionBetween(Column("id"), 1.databaseValue, 3.databaseValue) +struct SQLExpressionBetween : SQLExpression { + let expression: SQLExpression + let lowerBound: SQLExpression + let upperBound: SQLExpression + let isNegated: Bool + + init(_ expression: SQLExpression, _ lowerBound: SQLExpression, _ upperBound: SQLExpression, negated: Bool = false) { + self.expression = expression + self.lowerBound = lowerBound + self.upperBound = upperBound + self.isNegated = negated + } + + func expressionSQL(_ arguments: inout StatementArguments?) -> String { + return "(" + + expression.expressionSQL(&arguments) + + (isNegated ? " NOT BETWEEN " : " BETWEEN ") + + lowerBound.expressionSQL(&arguments) + + " AND " + + upperBound.expressionSQL(&arguments) + + ")" + } + + var negated: SQLExpression { + return SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated) + } +} + + +// MARK: - SQLExpressionFunction + +/// This type is an implementation detail of the query interface. +/// Do not use it directly. +/// +/// See https://github.com/groue/GRDB.swift/#the-query-interface +/// +/// # Low Level Query Interface +/// +/// SQLFunctionName is an SQL function name. +public struct SQLFunctionName : Hashable { + /// The SQL function name + public let sql: String + + /// Creates a function name + /// + /// SQLFunctionName("ABS") + public init(_ sql: String) { + self.sql = sql + } + + public var hashValue: Int { + return sql.hashValue + } +} + +public func ==(lhs: SQLFunctionName, rhs: SQLFunctionName) -> Bool { + return lhs.sql == rhs.sql +} + +/// This type is an implementation detail of the query interface. +/// Do not use it directly. +/// +/// See https://github.com/groue/GRDB.swift/#the-query-interface +/// +/// # Low Level Query Interface +/// +/// SQLExpressionFunction is an SQL function call. +/// +/// // ABS(-1) +/// SQLExpressionFunction(.abs, [-1.databaseValue]) +public struct SQLExpressionFunction : SQLExpression { + /// The function name + public let functionName: SQLFunctionName + + /// The function arguments + public let arguments: [SQLExpression] + + /// Creates an SQL function call + /// + /// // ABS(-1) + /// SQLExpressionFunction(.abs, arguments: [-1.databaseValue]) + public init(_ functionName: SQLFunctionName, arguments: [SQLExpression]) { + self.functionName = functionName + self.arguments = arguments + } + + /// Creates an SQL function call + /// + /// // ABS(-1) + /// SQLExpressionFunction(.abs, arguments: -1) + public init(_ functionName: SQLFunctionName, arguments: SQLExpressible...) { + self.init(functionName, arguments: arguments.map { $0.sqlExpression }) + } + + /// This function is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// See SQLExpression.expressionSQL(_:arguments:) + public func expressionSQL(_ arguments: inout StatementArguments?) -> String { + return functionName.sql + "(" + (self.arguments.map { $0.expressionSQL(&arguments) } as [String]).joined(separator: ", ") + ")" + } +} + + +// MARK: - SQLExpressionCount + +/// SQLExpressionCount is a call to the SQL `COUNT` function. +/// +/// // COUNT(name) +/// SQLExpressionCount(Column("name")) +struct SQLExpressionCount : SQLExpression { + /// The counted value + let counted: SQLSelectable + + init(_ counted: SQLSelectable) { + self.counted = counted + } + + func expressionSQL(_ arguments: inout StatementArguments?) -> String { + return "COUNT(" + counted.countedSQL(&arguments) + ")" + } +} + + +// MARK: - SQLExpressionCountDistinct + +/// SQLExpressionCountDistinct is a call to the SQL `COUNT(DISTINCT ...)` function. +/// +/// // COUNT(DISTINCT name) +/// SQLExpressionCountDistinct(Column("name")) +struct SQLExpressionCountDistinct : SQLExpression { + let counted: SQLExpression + + init(_ counted: SQLExpression) { + self.counted = counted + } + + func expressionSQL(_ arguments: inout StatementArguments?) -> String { + return "COUNT(DISTINCT " + counted.expressionSQL(&arguments) + ")" + } +} + + +// MARK: - SQLExpressionCollate + +/// SQLExpressionCollate is an expression tainted by an SQLite collation. +/// +/// // email = 'arthur@example.com' COLLATE NOCASE +/// SQLExpressionCollate(Column("email") == "arthur@example.com", "NOCASE") +struct SQLExpressionCollate : SQLExpression { + let expression: SQLExpression + let collationName: Database.CollationName + + init(_ expression: SQLExpression, collationName: Database.CollationName) { + self.expression = expression + self.collationName = collationName + } + + func expressionSQL(_ arguments: inout StatementArguments?) -> String { + let sql = expression.expressionSQL(&arguments) + let chars = sql.characters + if chars.last! == ")" { + return String(chars.prefix(upTo: chars.index(chars.endIndex, offsetBy: -1))) + " COLLATE " + collationName.rawValue + ")" + } else { + return sql + " COLLATE " + collationName.rawValue + } + } +} + diff --git a/GRDB/QueryInterface/SQLFunction.swift b/GRDB/QueryInterface/SQLFunction.swift deleted file mode 100644 index e17fc8b14..000000000 --- a/GRDB/QueryInterface/SQLFunction.swift +++ /dev/null @@ -1,179 +0,0 @@ -// MARK: - Custom Functions - -extension DatabaseFunction { - /// Returns an SQL expression that applies the function. - /// - /// See https://github.com/groue/GRDB.swift/#sql-functions - public func apply(_ arguments: SQLExpressible...) -> _SQLExpression { - return .function(name, arguments.map { $0.sqlExpression }) - } -} - - -// MARK: - ABS(...) - -/// Returns an SQL expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-functions -public func abs(_ value: _SpecificSQLExpressible) -> _SQLExpression { - return .function("ABS", [value.sqlExpression]) -} - - -// MARK: - AVG(...) - -/// Returns an SQL expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-functions -public func average(_ value: _SpecificSQLExpressible) -> _SQLExpression { - return .function("AVG", [value.sqlExpression]) -} - - -// MARK: - COUNT(...) - -/// Returns an SQL expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-functions -public func count(_ counted: _SQLSelectable) -> _SQLExpression { - return .count(counted) -} - - -// MARK: - COUNT(DISTINCT ...) - -/// Returns an SQL expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-functions -public func count(distinct value: _SpecificSQLExpressible) -> _SQLExpression { - return .countDistinct(value.sqlExpression) -} - - -// MARK: - IFNULL(...) - -/// Returns an SQL expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-functions -public func ?? (lhs: _SpecificSQLExpressible, rhs: SQLExpressible) -> _SQLExpression { - return .function("IFNULL", [lhs.sqlExpression, rhs.sqlExpression]) -} - -/// Returns an SQL expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-functions -public func ?? (lhs: SQLExpressible?, rhs: _SpecificSQLExpressible) -> _SQLExpression { - if let lhs = lhs { - return .function("IFNULL", [lhs.sqlExpression, rhs.sqlExpression]) - } else { - return rhs.sqlExpression - } -} - - -// MARK: - LENGTH(...) - -/// Returns an SQL expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-functions -public func length(_ value: _SpecificSQLExpressible) -> _SQLExpression { - return .function("LENGTH", [value.sqlExpression]) -} - - -// MARK: - MAX(...) - -/// Returns an SQL expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-functions -public func max(_ value: _SpecificSQLExpressible) -> _SQLExpression { - return .function("MAX", [value.sqlExpression]) -} - - -// MARK: - MIN(...) - -/// Returns an SQL expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-functions -public func min(_ value: _SpecificSQLExpressible) -> _SQLExpression { - return .function("MIN", [value.sqlExpression]) -} - - -// MARK: - SUM(...) - -/// Returns an SQL expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-functions -public func sum(_ value: _SpecificSQLExpressible) -> _SQLExpression { - return .function("SUM", [value.sqlExpression]) -} - - -// MARK: - Swift String functions - -extension _SpecificSQLExpressible { - /// Returns an SQL expression that applies the Swift's built-in - /// capitalized String property. It is NULL for non-String arguments. - /// - /// let nameColumn = Column("name") - /// let request = Person.select(nameColumn.capitalized) - /// let names = String.fetchAll(dbQueue, request) // [String] - public var capitalized: _SQLExpression { - return DatabaseFunction.capitalize.apply(sqlExpression) - } - - /// Returns an SQL expression that applies the Swift's built-in - /// lowercased String property. It is NULL for non-String arguments. - /// - /// let nameColumn = Column("name") - /// let request = Person.select(nameColumn.lowercased()) - /// let names = String.fetchAll(dbQueue, request) // [String] - public var lowercased: _SQLExpression { - return DatabaseFunction.lowercase.apply(sqlExpression) - } - - /// Returns an SQL expression that applies the Swift's built-in - /// uppercased String property. It is NULL for non-String arguments. - /// - /// let nameColumn = Column("name") - /// let request = Person.select(nameColumn.uppercased()) - /// let names = String.fetchAll(dbQueue, request) // [String] - public var uppercased: _SQLExpression { - return DatabaseFunction.uppercase.apply(sqlExpression) - } -} - -@available(iOS 9.0, OSX 10.11, *) -extension _SpecificSQLExpressible { - /// Returns an SQL expression that applies the Swift's built-in - /// localizedCapitalized String property. It is NULL for non-String arguments. - /// - /// let nameColumn = Column("name") - /// let request = Person.select(nameColumn.localizedCapitalized) - /// let names = String.fetchAll(dbQueue, request) // [String] - public var localizedCapitalized: _SQLExpression { - return DatabaseFunction.localizedCapitalize.apply(sqlExpression) - } - - /// Returns an SQL expression that applies the Swift's built-in - /// localizedLowercased String property. It is NULL for non-String arguments. - /// - /// let nameColumn = Column("name") - /// let request = Person.select(nameColumn.localizedLowercased) - /// let names = String.fetchAll(dbQueue, request) // [String] - public var localizedLowercased: _SQLExpression { - return DatabaseFunction.localizedLowercase.apply(sqlExpression) - } - - /// Returns an SQL expression that applies the Swift's built-in - /// localizedUppercased String property. It is NULL for non-String arguments. - /// - /// let nameColumn = Column("name") - /// let request = Person.select(nameColumn.localizedUppercased) - /// let names = String.fetchAll(dbQueue, request) // [String] - public var localizedUppercased: _SQLExpression { - return DatabaseFunction.localizedUppercase.apply(sqlExpression) - } -} diff --git a/GRDB/QueryInterface/SQLOperator.swift b/GRDB/QueryInterface/SQLOperator.swift deleted file mode 100644 index ac4c441ac..000000000 --- a/GRDB/QueryInterface/SQLOperator.swift +++ /dev/null @@ -1,470 +0,0 @@ -// MARK: - Operator = - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func == (lhs: _SpecificSQLExpressible, rhs: SQLExpressible?) -> _SQLExpression { - return .equalOperator(lhs.sqlExpression, rhs?.sqlExpression ?? .value(nil)) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func == (lhs: _SpecificSQLExpressible, rhs: Bool?) -> _SQLExpression { - if let rhs = rhs { - if rhs { - return lhs.sqlExpression - } else { - return .notOperator(lhs.sqlExpression) - } - } else { - return .equalOperator(lhs.sqlExpression, .value(nil)) - } -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func == (lhs: SQLExpressible?, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .equalOperator(lhs?.sqlExpression ?? .value(nil), rhs.sqlExpression) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func == (lhs: Bool?, rhs: _SpecificSQLExpressible) -> _SQLExpression { - if let lhs = lhs { - if lhs { - return rhs.sqlExpression - } else { - return .notOperator(rhs.sqlExpression) - } - } else { - return .equalOperator(.value(nil), rhs.sqlExpression) - } -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func == (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .equalOperator(lhs.sqlExpression, rhs.sqlExpression) -} - - -// MARK: - Operator != - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func != (lhs: _SpecificSQLExpressible, rhs: SQLExpressible?) -> _SQLExpression { - return .notEqualOperator(lhs.sqlExpression, rhs?.sqlExpression ?? .value(nil)) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func != (lhs: _SpecificSQLExpressible, rhs: Bool?) -> _SQLExpression { - if let rhs = rhs { - if rhs { - return .notOperator(lhs.sqlExpression) - } else { - return lhs.sqlExpression - } - } else { - return .notEqualOperator(lhs.sqlExpression, .value(nil)) - } -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func != (lhs: SQLExpressible?, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .notEqualOperator(lhs?.sqlExpression ?? .value(nil), rhs.sqlExpression) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func != (lhs: Bool?, rhs: _SpecificSQLExpressible) -> _SQLExpression { - if let lhs = lhs { - if lhs { - return .notOperator(rhs.sqlExpression) - } else { - return rhs.sqlExpression - } - } else { - return .notEqualOperator(.value(nil), rhs.sqlExpression) - } -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func != (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .notEqualOperator(lhs.sqlExpression, rhs.sqlExpression) -} - - -// MARK: - Operator < - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func < (lhs: _SpecificSQLExpressible, rhs: SQLExpressible) -> _SQLExpression { - return .infixOperator("<", lhs.sqlExpression, rhs.sqlExpression) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func < (lhs: SQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .infixOperator("<", lhs.sqlExpression, rhs.sqlExpression) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func < (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .infixOperator("<", lhs.sqlExpression, rhs.sqlExpression) -} - - -// MARK: - Operator <= - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func <= (lhs: _SpecificSQLExpressible, rhs: SQLExpressible) -> _SQLExpression { - return .infixOperator("<=", lhs.sqlExpression, rhs.sqlExpression) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func <= (lhs: SQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .infixOperator("<=", lhs.sqlExpression, rhs.sqlExpression) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func <= (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .infixOperator("<=", lhs.sqlExpression, rhs.sqlExpression) -} - - -// MARK: - Operator > - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func > (lhs: _SpecificSQLExpressible, rhs: SQLExpressible) -> _SQLExpression { - return .infixOperator(">", lhs.sqlExpression, rhs.sqlExpression) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func > (lhs: SQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .infixOperator(">", lhs.sqlExpression, rhs.sqlExpression) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func > (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .infixOperator(">", lhs.sqlExpression, rhs.sqlExpression) -} - - -// MARK: - Operator >= - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func >= (lhs: _SpecificSQLExpressible, rhs: SQLExpressible) -> _SQLExpression { - return .infixOperator(">=", lhs.sqlExpression, rhs.sqlExpression) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func >= (lhs: SQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .infixOperator(">=", lhs.sqlExpression, rhs.sqlExpression) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func >= (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .infixOperator(">=", lhs.sqlExpression, rhs.sqlExpression) -} - - -// MARK: - Operator * - -/// Returns an SQL arithmetic expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func * (lhs: _SpecificSQLExpressible, rhs: SQLExpressible) -> _SQLExpression { - return .infixOperator("*", lhs.sqlExpression, rhs.sqlExpression) -} - -/// Returns an SQL arithmetic expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func * (lhs: SQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .infixOperator("*", lhs.sqlExpression, rhs.sqlExpression) -} - -/// Returns an SQL arithmetic expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func * (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .infixOperator("*", lhs.sqlExpression, rhs.sqlExpression) -} - - -// MARK: - Operator / - -/// Returns an SQL arithmetic expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func / (lhs: _SpecificSQLExpressible, rhs: SQLExpressible) -> _SQLExpression { - return .infixOperator("/", lhs.sqlExpression, rhs.sqlExpression) -} - -/// Returns an SQL arithmetic expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func / (lhs: SQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .infixOperator("/", lhs.sqlExpression, rhs.sqlExpression) -} - -/// Returns an SQL arithmetic expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func / (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .infixOperator("/", lhs.sqlExpression, rhs.sqlExpression) -} - - -// MARK: - Operator + - -/// Returns an SQL arithmetic expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func + (lhs: _SpecificSQLExpressible, rhs: SQLExpressible) -> _SQLExpression { - return .infixOperator("+", lhs.sqlExpression, rhs.sqlExpression) -} - -/// Returns an SQL arithmetic expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func + (lhs: SQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .infixOperator("+", lhs.sqlExpression, rhs.sqlExpression) -} - -/// Returns an SQL arithmetic expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func + (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .infixOperator("+", lhs.sqlExpression, rhs.sqlExpression) -} - - -// MARK: - Operator - (prefix) - -/// Returns an SQL arithmetic expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public prefix func - (value: _SpecificSQLExpressible) -> _SQLExpression { - return .prefixOperator("-", value.sqlExpression) -} - - -// MARK: - Operator - (infix) - -/// Returns an SQL arithmetic expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func - (lhs: _SpecificSQLExpressible, rhs: SQLExpressible) -> _SQLExpression { - return .infixOperator("-", lhs.sqlExpression, rhs.sqlExpression) -} - -/// Returns an SQL arithmetic expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func - (lhs: SQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .infixOperator("-", lhs.sqlExpression, rhs.sqlExpression) -} - -/// Returns an SQL arithmetic expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func - (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .infixOperator("-", lhs.sqlExpression, rhs.sqlExpression) -} - - -// MARK: - Operator AND - -/// Returns an SQL logical expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func && (lhs: _SpecificSQLExpressible, rhs: SQLExpressible) -> _SQLExpression { - return .infixOperator("AND", lhs.sqlExpression, rhs.sqlExpression) -} - -/// Returns an SQL logical expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func && (lhs: SQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .infixOperator("AND", lhs.sqlExpression, rhs.sqlExpression) -} - -/// Returns an SQL logical expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func && (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .infixOperator("AND", lhs.sqlExpression, rhs.sqlExpression) -} - - -// MARK: - Operator BETWEEN - -extension Range where Bound: SQLExpressible { - /// Returns an SQL expression that checks the inclusion of a value in - /// a range. - /// - /// See https://github.com/groue/GRDB.swift/#sql-operators - public func contains(_ element: _SpecificSQLExpressible) -> _SQLExpression { - return (element >= lowerBound) && (element < upperBound) - } -} - -extension ClosedRange where Bound: SQLExpressible { - /// Returns an SQL expression that checks the inclusion of a value in - /// an range. - /// - /// See https://github.com/groue/GRDB.swift/#sql-operators - public func contains(_ element: _SpecificSQLExpressible) -> _SQLExpression { - return .between(value: element.sqlExpression, min: lowerBound.sqlExpression, max: upperBound.sqlExpression) - } -} - -extension CountableRange where Bound: SQLExpressible { - /// Returns an SQL expression that checks the inclusion of a value in - /// a range. - /// - /// See https://github.com/groue/GRDB.swift/#sql-operators - public func contains(_ element: _SpecificSQLExpressible) -> _SQLExpression { - return .between(value: element.sqlExpression, min: lowerBound.sqlExpression, max: upperBound.advanced(by: -1).sqlExpression) - } -} - -extension CountableClosedRange where Bound: SQLExpressible { - /// Returns an SQL expression that checks the inclusion of a value in - /// a range. - /// - /// See https://github.com/groue/GRDB.swift/#sql-operators - public func contains(_ element: _SpecificSQLExpressible) -> _SQLExpression { - return .between(value: element.sqlExpression, min: lowerBound.sqlExpression, max: upperBound.sqlExpression) - } -} - - -// MARK: - Operator IN - -extension Sequence where Self.Iterator.Element: SQLExpressible { - /// Returns an SQL expression that checks the inclusion of a value in - /// a sequence. - /// - /// See https://github.com/groue/GRDB.swift/#sql-operators - public func contains(_ element: _SpecificSQLExpressible) -> _SQLExpression { - return .inOperator(map { $0.sqlExpression }, element.sqlExpression) - } -} - - -// MARK: - Operator IS - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func === (lhs: _SpecificSQLExpressible, rhs: SQLExpressible?) -> _SQLExpression { - return .isOperator(lhs.sqlExpression, rhs?.sqlExpression ?? .value(nil)) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func === (lhs: SQLExpressible?, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .isOperator(lhs?.sqlExpression ?? .value(nil), rhs.sqlExpression) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func === (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .isOperator(lhs.sqlExpression, rhs.sqlExpression) -} - - -// MARK: - Operator IS NOT - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func !== (lhs: _SpecificSQLExpressible, rhs: SQLExpressible?) -> _SQLExpression { - return .isNotOperator(lhs.sqlExpression, rhs?.sqlExpression ?? .value(nil)) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func !== (lhs: SQLExpressible?, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .isNotOperator(lhs?.sqlExpression ?? .value(nil), rhs.sqlExpression) -} - -/// Returns an SQL expression that compares two values. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func !== (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .isNotOperator(lhs.sqlExpression, rhs.sqlExpression) -} - - -// MARK: - Operator OR - -/// Returns an SQL logical expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func || (lhs: _SpecificSQLExpressible, rhs: SQLExpressible) -> _SQLExpression { - return .infixOperator("OR", lhs.sqlExpression, rhs.sqlExpression) -} - -/// Returns an SQL logical expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func || (lhs: SQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .infixOperator("OR", lhs.sqlExpression, rhs.sqlExpression) -} - -/// Returns an SQL logical expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public func || (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression { - return .infixOperator("OR", lhs.sqlExpression, rhs.sqlExpression) -} - - -// MARK: - Operator NOT - -/// Returns an SQL logical expression. -/// -/// See https://github.com/groue/GRDB.swift/#sql-operators -public prefix func ! (value: _SpecificSQLExpressible) -> _SQLExpression { - return .notOperator(value.sqlExpression) -} diff --git a/GRDB/QueryInterface/SQLOrderingTerm.swift b/GRDB/QueryInterface/SQLOrderingTerm.swift new file mode 100644 index 000000000..5a17ca81b --- /dev/null +++ b/GRDB/QueryInterface/SQLOrderingTerm.swift @@ -0,0 +1,90 @@ +// MARK: - SQLOrderingTerm + +/// This protocol is an implementation detail of the query interface. +/// Do not use it directly. +/// +/// See https://github.com/groue/GRDB.swift/#the-query-interface +/// +/// # Low Level Query Interface +/// +/// The protocol for all types that can be used as an SQL ordering term, as +/// described at https://www.sqlite.org/syntax/ordering-term.html +public protocol SQLOrderingTerm { + var reversed: SQLOrderingTerm { get } + func orderingTermSQL(_ arguments: inout StatementArguments?) -> String +} + + +// MARK: - SQLOrdering + +enum SQLOrdering : SQLOrderingTerm { + case asc(SQLExpression) + case desc(SQLExpression) + + var reversed: SQLOrderingTerm { + switch self { + case .asc(let expression): + return SQLOrdering.desc(expression) + case .desc(let expression): + return SQLOrdering.asc(expression) + } + } + + func orderingTermSQL(_ arguments: inout StatementArguments?) -> String { + switch self { + case .asc(let expression): + return expression.expressionSQL(&arguments) + " ASC" + case .desc(let expression): + return expression.expressionSQL(&arguments) + " DESC" + } + } +} + + +// MARK: - SQLExpressible + +extension SQLExpressible where Self: SQLOrderingTerm { + + /// This property is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// See SQLOrderingTerm.reversed + public var reversed: SQLOrderingTerm { + return SQLOrdering.desc(sqlExpression) + } + + /// This method is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// See SQLOrderingTerm.orderingTermSQL(_) + public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String { + return sqlExpression.expressionSQL(&arguments) + } +} + + +// MARK: - SQLCollatedExpression + +extension SQLCollatedExpression : SQLOrderingTerm { + + /// Returns self.desc + public var reversed: SQLOrderingTerm { + return desc + } + + /// This method is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String { + return sqlExpression.orderingTermSQL(&arguments) + } +} diff --git a/GRDB/QueryInterface/SQLSelectQuery.swift b/GRDB/QueryInterface/SQLSelectQuery.swift index c1d2fbfb3..22f2fa95d 100644 --- a/GRDB/QueryInterface/SQLSelectQuery.swift +++ b/GRDB/QueryInterface/SQLSelectQuery.swift @@ -1,749 +1,92 @@ -#if !USING_BUILTIN_SQLITE - #if os(OSX) - import SQLiteMacOSX - #elseif os(iOS) - #if (arch(i386) || arch(x86_64)) - import SQLiteiPhoneSimulator - #else - import SQLiteiPhoneOS - #endif - #elseif os(watchOS) - #if (arch(i386) || arch(x86_64)) - import SQLiteWatchSimulator - #else - import SQLiteWatchOS - #endif - #endif -#endif +// MARK: - SQLSelectQuery - -// MARK: - _SQLSelectQuery - -/// This type is an implementation detail of the query interface. +/// This protocol is an implementation detail of the query interface. /// Do not use it directly. /// /// See https://github.com/groue/GRDB.swift/#the-query-interface -public struct _SQLSelectQuery { - var selection: [_SQLSelectable] - var isDistinct: Bool - var source: _SQLSource? - var whereExpression: _SQLExpression? - var groupByExpressions: [_SQLExpression] - var orderings: [_SQLOrderable] - var isReversed: Bool - var havingExpression: _SQLExpression? - var limit: _SQLLimit? +/// +/// # Low Level Query Interface +/// +/// SQLSelectQuery is the protocol for types that represent a full select query. +public protocol SQLSelectQuery : FetchRequest, SQLCollection { - init( - select selection: [_SQLSelectable], - isDistinct: Bool = false, - from source: _SQLSource? = nil, - filter whereExpression: _SQLExpression? = nil, - groupBy groupByExpressions: [_SQLExpression] = [], - orderBy orderings: [_SQLOrderable] = [], - isReversed: Bool = false, - having havingExpression: _SQLExpression? = nil, - limit: _SQLLimit? = nil) - { - self.selection = selection - self.isDistinct = isDistinct - self.source = source - self.whereExpression = whereExpression - self.groupByExpressions = groupByExpressions - self.orderings = orderings - self.isReversed = isReversed - self.havingExpression = havingExpression - self.limit = limit - } - - func sql(_ arguments: inout StatementArguments?) -> String { - var sql = "SELECT" - - if isDistinct { - sql += " DISTINCT" - } - - assert(!selection.isEmpty) - sql += " " + selection.map { $0.resultColumnSQL(&arguments) }.joined(separator: ", ") - - if let source = source { - sql += " FROM " + source.sql(&arguments) - } - - if let whereExpression = whereExpression { - sql += " WHERE " + whereExpression.sql(&arguments) - } - - if !groupByExpressions.isEmpty { - sql += " GROUP BY " + groupByExpressions.map { $0.sql(&arguments) }.joined(separator: ", ") - } - - if let havingExpression = havingExpression { - sql += " HAVING " + havingExpression.sql(&arguments) - } - - var orderings = self.orderings - if isReversed { - if orderings.isEmpty { - // https://www.sqlite.org/lang_createtable.html#rowid - // - // > The rowid value can be accessed using one of the special - // > case-independent names "rowid", "oid", or "_rowid_" in - // > place of a column name. If a table contains a user defined - // > column named "rowid", "oid" or "_rowid_", then that name - // > always refers the explicitly declared column and cannot be - // > used to retrieve the integer rowid value. - // - // Here we assume that _rowid_ is not a custom column. - // TODO: support for user-defined _rowid_ column. - // TODO: support for WITHOUT ROWID tables. - orderings = [Column("_rowid_").desc] - } else { - orderings = orderings.map { $0.reversedOrdering } - } - } - if !orderings.isEmpty { - sql += " ORDER BY " + orderings.map { $0.orderingSQL(&arguments) }.joined(separator: ", ") - } - - if let limit = limit { - sql += " LIMIT " + limit.sql - } - - return sql - } - - /// Returns a query that counts the number of rows matched by self. - var countQuery: _SQLSelectQuery { - guard groupByExpressions.isEmpty && limit == nil else { - // SELECT ... GROUP BY ... - // SELECT ... LIMIT ... - return trivialCountQuery - } - - guard let source = source, case .table(name: let tableName, alias: let alias) = source else { - // SELECT ... FROM (something which is not a table) - return trivialCountQuery - } - - assert(!selection.isEmpty) - if selection.count == 1 { - let selectable = self.selection[0] - switch selectable.sqlSelectableKind { - case .star(sourceName: let sourceName): - guard !isDistinct else { - return trivialCountQuery - } - - if let sourceName = sourceName { - guard sourceName == tableName || sourceName == alias else { - return trivialCountQuery - } - } - - // SELECT * FROM tableName ... - // -> - // SELECT COUNT(*) FROM tableName ... - var countQuery = unorderedQuery - countQuery.selection = [_SQLExpression.count(selectable)] - return countQuery - - case .expression(let expression): - // SELECT [DISTINCT] expr FROM tableName ... - if isDistinct { - // SELECT DISTINCT expr FROM tableName ... - // -> - // SELECT COUNT(DISTINCT expr) FROM tableName ... - var countQuery = unorderedQuery - countQuery.isDistinct = false - countQuery.selection = [_SQLExpression.countDistinct(expression)] - return countQuery - } else { - // SELECT expr FROM tableName ... - // -> - // SELECT COUNT(*) FROM tableName ... - var countQuery = unorderedQuery - countQuery.selection = [_SQLExpression.count(_SQLResultColumn.star(nil))] - return countQuery - } - } - } else { - // SELECT [DISTINCT] expr1, expr2, ... FROM tableName ... - - guard !isDistinct else { - return trivialCountQuery - } + /// This function is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// Returns the SQL string of the select query. + /// + /// When the arguments parameter is nil, any value must be written down as + /// a literal in the returned SQL. + /// + /// When the arguments parameter is not nil, then values may be replaced by + /// `?` or colon-prefixed tokens, and fed into arguments. + func selectQuerySQL(_ arguments: inout StatementArguments?) -> String +} - // SELECT expr1, expr2, ... FROM tableName ... - // -> - // SELECT COUNT(*) FROM tableName ... - var countQuery = unorderedQuery - countQuery.selection = [_SQLExpression.count(_SQLResultColumn.star(nil))] - return countQuery - } - } +extension SQLSelectQuery { - func makeDeleteStatement(_ db: Database) -> UpdateStatement { - guard groupByExpressions.isEmpty else { - fatalError("Can't delete query with GROUP BY expression") - } - - guard havingExpression == nil else { - fatalError("Can't delete query with GROUP BY expression") - } - - guard limit == nil else { - fatalError("Can't delete query with limit") - } - - var sql = "DELETE" + /// Returns an SQL expression that checks whether the receiver, as a + /// subquery, returns any row. + /// + /// + /// let request = Person.all() + /// request.exists() // EXISTS (SELECT * FROM persons) + public func exists() -> SQLExpression { + return SQLExpressionExists(self) + } +} + + +// MARK: - SQLCollection adoption + +extension SQLSelectQuery { + + /// This function is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// See SQLCollection.collectionSQL(_) + public func collectionSQL(_ arguments: inout StatementArguments?) -> String { + return selectQuerySQL(&arguments) + } +} + + +// MARK: - FetchRequest adoption + +extension SQLSelectQuery { + + /// A tuple that contains a prepared statement that is ready to be + /// executed, and an eventual row adapter. + public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { var arguments: StatementArguments? = StatementArguments() - - if let source = source { - sql += " FROM " + source.sql(&arguments) - } - - if let whereExpression = whereExpression { - sql += " WHERE " + whereExpression.sql(&arguments) - } - - let statement = try! db.makeUpdateStatement(sql) - statement.arguments = arguments! - return statement - } - - // SELECT COUNT(*) FROM (self) - private var trivialCountQuery: _SQLSelectQuery { - return _SQLSelectQuery( - select: [_SQLExpression.count(_SQLResultColumn.star(nil))], - from: .query(query: unorderedQuery, alias: nil)) - } - - /// Remove ordering - private var unorderedQuery: _SQLSelectQuery { - var query = self - query.isReversed = false - query.orderings = [] - return query + let sql = self.selectQuerySQL(&arguments) + let statement = try db.makeSelectStatement(sql) + try statement.setArgumentsWithValidation(arguments!) + return (statement, nil) } } -// MARK: - _SQLSource +// MARK: - QueryInterfaceSelectQueryDefinition -indirect enum _SQLSource { - case table(name: String, alias: String?) - case query(query: _SQLSelectQuery, alias: String?) - - func sql(_ arguments: inout StatementArguments?) -> String { - switch self { - case .table(let table, let alias): - if let alias = alias { - return table.quotedDatabaseIdentifier + " AS " + alias.quotedDatabaseIdentifier - } else { - return table.quotedDatabaseIdentifier - } - case .query(let query, let alias): - if let alias = alias { - return "(" + query.sql(&arguments) + ") AS " + alias.quotedDatabaseIdentifier - } else { - return "(" + query.sql(&arguments) + ")" - } - } - } -} - - -// MARK: - _SQLOrderable - -/// This protocol is an implementation detail of the query interface. -/// Do not use it directly. -/// -/// See https://github.com/groue/GRDB.swift/#the-query-interface -public protocol _SQLOrderable { - var reversedOrdering: _SQLOrderingExpression { get } - func orderingSQL(_ arguments: inout StatementArguments?) -> String -} - -/// This type is an implementation detail of the query interface. -/// Do not use it directly. -/// -/// See https://github.com/groue/GRDB.swift/#the-query-interface -public enum _SQLOrderingExpression { - case asc(_SQLExpression) - case desc(_SQLExpression) -} - -extension _SQLOrderingExpression : _SQLOrderable { - - /// This property is an implementation detail of the query interface. +extension QueryInterfaceSelectQueryDefinition : SQLSelectQuery { + /// This function is an implementation detail of the query interface. /// Do not use it directly. /// /// See https://github.com/groue/GRDB.swift/#the-query-interface - public var reversedOrdering: _SQLOrderingExpression { - switch self { - case .asc(let expression): - return .desc(expression) - case .desc(let expression): - return .asc(expression) - } - } - - /// This method is an implementation detail of the query interface. - /// Do not use it directly. /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface - public func orderingSQL(_ arguments: inout StatementArguments?) -> String { - switch self { - case .asc(let expression): - return expression.sql(&arguments) + " ASC" - case .desc(let expression): - return expression.sql(&arguments) + " DESC" - } - } -} - - -// MARK: - _SQLLimit - -struct _SQLLimit { - let limit: Int - let offset: Int? - - var sql: String { - if let offset = offset { - return "\(limit) OFFSET \(offset)" - } else { - return "\(limit)" - } - } -} - - -// MARK: - _SpecificSQLExpressible - -/// This protocol is an implementation detail of the query interface. -/// Do not use it directly. -/// -/// See https://github.com/groue/GRDB.swift/#the-query-interface -public protocol _SpecificSQLExpressible : SQLExpressible { - // SQLExpressible can be adopted by Swift standard types, and user - // types, through the DatabaseValueConvertible protocol which inherits - // from SQLExpressible. - // - // For example, Int adopts SQLExpressible through - // DatabaseValueConvertible. - // - // _SpecificSQLExpressible, on the other side, is not adopted by any - // Swift standard type or any user type. It is only adopted by GRDB types, - // such as Column and _SQLExpression. - // - // This separation lets us define functions and operators that do not - // spill out. The three declarations below have no chance overloading a - // Swift-defined operator, or a user-defined operator: - // - // - ==(SQLExpressible, _SpecificSQLExpressible) - // - ==(_SpecificSQLExpressible, SQLExpressible) - // - ==(_SpecificSQLExpressible, _SpecificSQLExpressible) -} - -extension _SpecificSQLExpressible where Self: _SQLOrderable { - - /// This property is an implementation detail of the query interface. - /// Do not use it directly. + /// # Low Level Query Interface /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface - public var reversedOrdering: _SQLOrderingExpression { - return .desc(sqlExpression) - } - - /// This method is an implementation detail of the query interface. - /// Do not use it directly. - /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface - public func orderingSQL(_ arguments: inout StatementArguments?) -> String { - return sqlExpression.sql(&arguments) + /// See SQLSelectQuery.selectQuerySQL(_:arguments:) + func selectQuerySQL(_ arguments: inout StatementArguments?) -> String { + return sql(&arguments) } } - -extension _SpecificSQLExpressible where Self: _SQLSelectable { - - /// This method is an implementation detail of the query interface. - /// Do not use it directly. - /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface - public func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { - return sqlExpression.sql(&arguments) - } - - /// This method is an implementation detail of the query interface. - /// Do not use it directly. - /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface - public func countedSQL(_ arguments: inout StatementArguments?) -> String { - return sqlExpression.sql(&arguments) - } - - /// This property is an implementation detail of the query interface. - /// Do not use it directly. - /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface - public var sqlSelectableKind: _SQLSelectableKind { - return .expression(sqlExpression) - } -} - -extension _SpecificSQLExpressible { - - /// Returns a value that can be used as an argument to FetchRequest.order() - /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface - public var asc: _SQLOrderingExpression { - return .asc(sqlExpression) - } - - /// Returns a value that can be used as an argument to FetchRequest.order() - /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface - public var desc: _SQLOrderingExpression { - return .desc(sqlExpression) - } - - /// Returns a value that can be used as an argument to FetchRequest.select() - /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface - public func aliased(_ alias: String) -> _SQLSelectable { - return _SQLResultColumn.expression(expression: sqlExpression, alias: alias) - } -} - - -/// This type is an implementation detail of the query interface. -/// Do not use it directly. -/// -/// See https://github.com/groue/GRDB.swift/#the-query-interface -public indirect enum _SQLExpression { - /// For example: `name || 'rrr' AS pirateName` - case sqlLiteral(String, StatementArguments?) - - /// For example: `1` or `'foo'` - case value(DatabaseValueConvertible?) // TODO: switch to DatabaseValue? - - /// For example: `name`, `table.name` - case identifier(identifier: String, sourceName: String?) - - /// For example: `name = 'foo' COLLATE NOCASE` - case collate(_SQLExpression, String) - - /// For example: `NOT condition` - case notOperator(_SQLExpression) - - /// For example: `name = 'foo'` - case equalOperator(_SQLExpression, _SQLExpression) - - /// For example: `name <> 'foo'` - case notEqualOperator(_SQLExpression, _SQLExpression) - - /// For example: `name IS NULL` - case isOperator(_SQLExpression, _SQLExpression) - - /// For example: `name IS NOT NULL` - case isNotOperator(_SQLExpression, _SQLExpression) - - /// For example: `-value` - case prefixOperator(String, _SQLExpression) - - /// For example: `age + 1` - case infixOperator(String, _SQLExpression, _SQLExpression) - - /// For example: `id IN (1,2,3)` - case inOperator([_SQLExpression], _SQLExpression) - - /// For example `id IN (SELECT ...)` - case inSubQuery(_SQLSelectQuery, _SQLExpression) - - /// For example `EXISTS (SELECT ...)` - case exists(_SQLSelectQuery) - - /// For example: `age BETWEEN 1 AND 2` - case between(value: _SQLExpression, min: _SQLExpression, max: _SQLExpression) - - /// For example: `LOWER(name)` - case function(String, [_SQLExpression]) - - /// For example: `COUNT(*)` - case count(_SQLSelectable) - - /// For example: `COUNT(DISTINCT name)` - case countDistinct(_SQLExpression) - - /// - func sql(_ arguments: inout StatementArguments?) -> String { - switch self { - case .sqlLiteral(let sql, let literalArguments): - if let literalArguments = literalArguments { - guard arguments != nil else { - fatalError("Not implemented") - } - arguments!.values.append(contentsOf: literalArguments.values) - for (name, value) in literalArguments.namedValues { - guard arguments!.namedValues[name] == nil else { - fatalError("argument \(String(reflecting: name)) can't be reused") - } - arguments!.namedValues[name] = value - } - } - return sql - - case .value(let value): - guard let value = value else { - return "NULL" - } - if arguments == nil { - return value.sqlLiteral - } else { - arguments!.values.append(value) - return "?" - } - - case .identifier(let identifier, let sourceName): - if let sourceName = sourceName { - return sourceName.quotedDatabaseIdentifier + "." + identifier.quotedDatabaseIdentifier - } else { - return identifier.quotedDatabaseIdentifier - } - - case .collate(let expression, let collation): - let sql = expression.sql(&arguments) - let chars = sql.characters - if chars.last! == ")" { - return String(chars.prefix(upTo: chars.index(chars.endIndex, offsetBy: -1))) + " COLLATE " + collation + ")" - } else { - return sql + " COLLATE " + collation - } - - case .notOperator(let condition): - switch condition { - case .notOperator(let expression): - return expression.sql(&arguments) - - case .inOperator(let expressions, let expression): - if expressions.isEmpty { - return "1" - } else { - return "(" + expression.sql(&arguments) + " NOT IN (" + (expressions.map { $0.sql(&arguments) } as [String]).joined(separator: ", ") + "))" - } - - case .inSubQuery(let subQuery, let expression): - return "(" + expression.sql(&arguments) + " NOT IN (" + subQuery.sql(&arguments) + "))" - - case .exists(let subQuery): - return "(NOT EXISTS (" + subQuery.sql(&arguments) + "))" - - case .equalOperator(let lhs, let rhs): - return _SQLExpression.notEqualOperator(lhs, rhs).sql(&arguments) - - case .notEqualOperator(let lhs, let rhs): - return _SQLExpression.equalOperator(lhs, rhs).sql(&arguments) - - case .isOperator(let lhs, let rhs): - return _SQLExpression.isNotOperator(lhs, rhs).sql(&arguments) - - case .isNotOperator(let lhs, let rhs): - return _SQLExpression.isOperator(lhs, rhs).sql(&arguments) - - default: - return "(NOT " + condition.sql(&arguments) + ")" - } - - case .equalOperator(let lhs, let rhs): - switch (lhs, rhs) { - case (let lhs, .value(let rhs)) where rhs == nil: - // Swiftism! - // Turn `filter(a == nil)` into `a IS NULL` since the intention is obviously to check for NULL. `a = NULL` would evaluate to NULL. - return "(" + lhs.sql(&arguments) + " IS NULL)" - case (.value(let lhs), let rhs) where lhs == nil: - // Swiftism! - return "(" + rhs.sql(&arguments) + " IS NULL)" - default: - return "(" + lhs.sql(&arguments) + " = " + rhs.sql(&arguments) + ")" - } - - case .notEqualOperator(let lhs, let rhs): - switch (lhs, rhs) { - case (let lhs, .value(let rhs)) where rhs == nil: - // Swiftism! - // Turn `filter(a != nil)` into `a IS NOT NULL` since the intention is obviously to check for NULL. `a <> NULL` would evaluate to NULL. - return "(" + lhs.sql(&arguments) + " IS NOT NULL)" - case (.value(let lhs), let rhs) where lhs == nil: - // Swiftism! - return "(" + rhs.sql(&arguments) + " IS NOT NULL)" - default: - return "(" + lhs.sql(&arguments) + " <> " + rhs.sql(&arguments) + ")" - } - - case .isOperator(let lhs, let rhs): - switch (lhs, rhs) { - case (let lhs, .value(let rhs)) where rhs == nil: - return "(" + lhs.sql(&arguments) + " IS NULL)" - case (.value(let lhs), let rhs) where lhs == nil: - return "(" + rhs.sql(&arguments) + " IS NULL)" - default: - return "(" + lhs.sql(&arguments) + " IS " + rhs.sql(&arguments) + ")" - } - - case .isNotOperator(let lhs, let rhs): - switch (lhs, rhs) { - case (let lhs, .value(let rhs)) where rhs == nil: - return "(" + lhs.sql(&arguments) + " IS NOT NULL)" - case (.value(let lhs), let rhs) where lhs == nil: - return "(" + rhs.sql(&arguments) + " IS NOT NULL)" - default: - return "(" + lhs.sql(&arguments) + " IS NOT " + rhs.sql(&arguments) + ")" - } - - case .prefixOperator(let SQLOperator, let value): - return SQLOperator + value.sql(&arguments) - - case .infixOperator(let SQLOperator, let lhs, let rhs): - return "(" + lhs.sql(&arguments) + " \(SQLOperator) " + rhs.sql(&arguments) + ")" - - case .inOperator(let expressions, let expression): - guard !expressions.isEmpty else { - return "0" - } - return "(" + expression.sql(&arguments) + " IN (" + (expressions.map { $0.sql(&arguments) } as [String]).joined(separator: ", ") + "))" - - case .inSubQuery(let subQuery, let expression): - return "(" + expression.sql(&arguments) + " IN (" + subQuery.sql(&arguments) + "))" - - case .exists(let subQuery): - return "(EXISTS (" + subQuery.sql(&arguments) + "))" - - case .between(value: let value, min: let min, max: let max): - return "(" + value.sql(&arguments) + " BETWEEN " + min.sql(&arguments) + " AND " + max.sql(&arguments) + ")" - - case .function(let functionName, let functionArguments): - return functionName + "(" + (functionArguments.map { $0.sql(&arguments) } as [String]).joined(separator: ", ") + ")" - - case .count(let counted): - return "COUNT(" + counted.countedSQL(&arguments) + ")" - - case .countDistinct(let expression): - return "COUNT(DISTINCT " + expression.sql(&arguments) + ")" - } - } -} - -extension _SQLExpression : _SpecificSQLExpressible { - - /// This property is an implementation detail of the query interface. - /// Do not use it directly. - /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface - public var sqlExpression: _SQLExpression { - return self - } -} - -extension _SQLExpression : _SQLSelectable {} -extension _SQLExpression : _SQLOrderable {} - - -// MARK: - _SQLSelectable - -/// This protocol is an implementation detail of the query interface. -/// Do not use it directly. -/// -/// See https://github.com/groue/GRDB.swift/#the-query-interface -public protocol _SQLSelectable { - func resultColumnSQL(_ arguments: inout StatementArguments?) -> String - func countedSQL(_ arguments: inout StatementArguments?) -> String - var sqlSelectableKind: _SQLSelectableKind { get } -} - -/// This type is an implementation detail of the query interface. -/// Do not use it directly. -/// -/// See https://github.com/groue/GRDB.swift/#the-query-interface -public enum _SQLSelectableKind { - case expression(_SQLExpression) - case star(sourceName: String?) -} - -enum _SQLResultColumn { - case star(String?) - case expression(expression: _SQLExpression, alias: String) -} - -extension _SQLResultColumn : _SQLSelectable { - - func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { - switch self { - case .star(let sourceName): - if let sourceName = sourceName { - return sourceName.quotedDatabaseIdentifier + ".*" - } else { - return "*" - } - case .expression(expression: let expression, alias: let alias): - return expression.sql(&arguments) + " AS " + alias.quotedDatabaseIdentifier - } - } - - func countedSQL(_ arguments: inout StatementArguments?) -> String { - switch self { - case .star: - return "*" - case .expression(expression: let expression, alias: _): - return expression.sql(&arguments) - } - } - - var sqlSelectableKind: _SQLSelectableKind { - switch self { - case .star(let sourceName): - return .star(sourceName: sourceName) - case .expression(expression: let expression, alias: _): - return .expression(expression) - } - } -} - - -// MARK: - Column - -/// A column in the database -/// -/// See https://github.com/groue/GRDB.swift#the-query-interface -public struct Column { - let sourceName: String? - - /// The name of the column - public let name: String - - /// Initializes a column given its name. - public init(_ name: String) { - self.name = name - self.sourceName = nil - } - - init(_ name: String, sourceName: String?) { - self.name = name - self.sourceName = sourceName - } -} - -extension Column : _SpecificSQLExpressible { - - /// This property is an implementation detail of the query interface. - /// Do not use it directly. - /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface - public var sqlExpression: _SQLExpression { - return .identifier(identifier: name, sourceName: sourceName) - } -} - -extension Column : _SQLSelectable {} -extension Column : _SQLOrderable {} diff --git a/GRDB/QueryInterface/SQLSelectable.swift b/GRDB/QueryInterface/SQLSelectable.swift new file mode 100644 index 000000000..ef7d1c7d1 --- /dev/null +++ b/GRDB/QueryInterface/SQLSelectable.swift @@ -0,0 +1,114 @@ +// MARK: - SQLSelectable + +/// This protocol is an implementation detail of the query interface. +/// Do not use it directly. +/// +/// See https://github.com/groue/GRDB.swift/#the-query-interface +/// +/// # Low Level Query Interface +/// +/// SQLSelectable is the protocol for types that can be selected, as +/// described at https://www.sqlite.org/syntax/result-column.html +public protocol SQLSelectable { + func resultColumnSQL(_ arguments: inout StatementArguments?) -> String + func countedSQL(_ arguments: inout StatementArguments?) -> String + func countingSelectable(distinct: Bool, from tableName: String, aliased alias: String?) -> SQLSelectable? +} + + +// MARK: - SQLStar + +struct SQLStar : SQLSelectable { + fileprivate init() { + } + + func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { + return "*" + } + + func countedSQL(_ arguments: inout StatementArguments?) -> String { + return "*" + } + + public func countingSelectable(distinct: Bool, from tableName: String, aliased alias: String?) -> SQLSelectable? { + // SELECT DISTINCT * FROM tableName ... + guard !distinct else { + return nil + } + + // SELECT * FROM tableName ... + // -> + // SELECT COUNT(*) FROM tableName ... + return SQLExpressionCount(self) + } +} + +let star = SQLStar() + + +// MARK: - SQLAliasedExpression + +struct SQLAliasedExpression : SQLSelectable { + let expression: SQLExpression + let alias: String + + init(_ expression: SQLExpression, alias: String) { + self.expression = expression + self.alias = alias + } + + func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { + return expression.resultColumnSQL(&arguments) + " AS " + alias.quotedDatabaseIdentifier + } + + func countedSQL(_ arguments: inout StatementArguments?) -> String { + return expression.countedSQL(&arguments) + } + + public func countingSelectable(distinct: Bool, from tableName: String, aliased alias: String?) -> SQLSelectable? { + return expression.countingSelectable(distinct: distinct, from: tableName, aliased: alias) + } +} + + +// MARK: - SQLExpressible + +extension SQLExpressible where Self: SQLSelectable { + + /// This method is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// See SQLSelectable.resultColumnSQL(_) + public func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { + return sqlExpression.expressionSQL(&arguments) + } + + /// This method is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// See SQLSelectable.countedSQL(_) + public func countedSQL(_ arguments: inout StatementArguments?) -> String { + return sqlExpression.expressionSQL(&arguments) + } + + + /// This method is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// + /// # Low Level Query Interface + /// + /// See SQLSelectable.countingSelectable(distinct:from:aliased:) + public func countingSelectable(distinct: Bool, from tableName: String, aliased alias: String?) -> SQLSelectable? { + return sqlExpression.countingSelectable(distinct: distinct, from: tableName, aliased: alias) + } +} diff --git a/GRDB/QueryInterface/SQLSpecificExpressible.swift b/GRDB/QueryInterface/SQLSpecificExpressible.swift new file mode 100644 index 000000000..1da9ae442 --- /dev/null +++ b/GRDB/QueryInterface/SQLSpecificExpressible.swift @@ -0,0 +1,92 @@ +/// This protocol is an implementation detail of the query interface. +/// Do not use it directly. +/// +/// See https://github.com/groue/GRDB.swift/#the-query-interface +/// +/// # Low Level Query Interface +/// +/// SQLSpecificExpressible is a protocol for all query interface types that can +/// be turned into an SQL expression. Other types whose existence is not purely +/// dedicated to the query interface should adopt the SQLExpressible +/// protocol instead. +/// +/// For example, Column is a type that only exists to help you build requests, +/// and it adopts SQLSpecificExpressible. +/// +/// On the other side, Int adopts SQLExpressible (via DatabaseValueConvertible). +public protocol SQLSpecificExpressible : SQLExpressible { + // SQLExpressible can be adopted by Swift standard types, and user + // types, through the DatabaseValueConvertible protocol which inherits + // from SQLExpressible. + // + // For example, Int adopts SQLExpressible through + // DatabaseValueConvertible. + // + // SQLSpecificExpressible, on the other side, is not adopted by any + // Swift standard type or any user type. It is only adopted by GRDB types, + // such as Column and SQLExpression. + // + // This separation lets us define functions and operators that do not + // spill out. The three declarations below have no chance overloading a + // Swift-defined operator, or a user-defined operator: + // + // - ==(SQLExpressible, SQLSpecificExpressible) + // - ==(SQLSpecificExpressible, SQLExpressible) + // - ==(SQLSpecificExpressible, SQLSpecificExpressible) +} + + +// MARK: - SQL Ordering Support + +extension SQLSpecificExpressible { + + /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + public var asc: SQLOrderingTerm { + return SQLOrdering.asc(sqlExpression) + } + + /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + public var desc: SQLOrderingTerm { + return SQLOrdering.desc(sqlExpression) + } +} + + +// MARK: - SQL Selection Support + +extension SQLSpecificExpressible { + + /// Returns a value that can be used as an argument to FetchRequest.select() + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + public func aliased(_ alias: String) -> SQLSelectable { + return SQLAliasedExpression(sqlExpression, alias: alias) + } +} + + +// MARK: - SQL Collations Support + +extension SQLSpecificExpressible { + + /// This method is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + public func collating(_ collation: Database.CollationName) -> SQLCollatedExpression { + return SQLCollatedExpression(sqlExpression, collationName: collation) + } + + /// This method is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + public func collating(_ collation: DatabaseCollation) -> SQLCollatedExpression { + return SQLCollatedExpression(sqlExpression, collationName: Database.CollationName(collation.name)) + } +} + diff --git a/GRDB/QueryInterface/Support/SQLFunctions.swift b/GRDB/QueryInterface/Support/SQLFunctions.swift new file mode 100644 index 000000000..0d9170d51 --- /dev/null +++ b/GRDB/QueryInterface/Support/SQLFunctions.swift @@ -0,0 +1,212 @@ +// MARK: - Custom Functions + +extension DatabaseFunction { + /// Returns an SQL expression that applies the function. + /// + /// See https://github.com/groue/GRDB.swift/#sql-functions + public func apply(_ arguments: SQLExpressible...) -> SQLExpression { + return SQLExpressionFunction(SQLFunctionName(name), arguments: arguments.map { $0.sqlExpression }) + } +} + + +// MARK: - ABS(...) + +extension SQLFunctionName { + /// The `ABS` function name + public static let abs = SQLFunctionName("ABS") +} + +/// Returns an expression that evaluates the `ABS` SQL function. +/// +/// // ABS(amount) +/// abs(Column("amount")) +public func abs(_ value: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionFunction(.abs, arguments: value) +} + + +// MARK: - AVG(...) + +extension SQLFunctionName { + /// The `AVG` function name + public static let avg = SQLFunctionName("AVG") +} + +/// Returns an expression that evaluates the `AVG` SQL function. +/// +/// // AVG(length) +/// average(Column("length")) +public func average(_ value: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionFunction(.avg, arguments: value) +} + + +// MARK: - COUNT(...) + +/// Returns an expression that evaluates the `COUNT` SQL function. +/// +/// // COUNT(email) +/// count(Column("email")) +public func count(_ counted: SQLSelectable) -> SQLExpression { + return SQLExpressionCount(counted) +} + + +// MARK: - COUNT(DISTINCT ...) + +/// Returns an expression that evaluates the `COUNT(DISTINCT)` SQL function. +/// +/// // COUNT(DISTINCT email) +/// count(distinct: Column("email")) +public func count(distinct value: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionCountDistinct(value.sqlExpression) +} + + +// MARK: - IFNULL(...) + +extension SQLFunctionName { + /// The `IFNULL` function name + public static let ifNull = SQLFunctionName("IFNULL") +} + +/// Returns an expression that evaluates the `IFNULL` SQL function. +/// +/// // IFNULL(name, 'Anonymous') +/// Column("name") ?? "Anonymous" +public func ?? (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { + return SQLExpressionFunction(.ifNull, arguments: lhs, rhs) +} + + +// MARK: - LENGTH(...) + +extension SQLFunctionName { + /// The `LENGTH` function name + public static let length = SQLFunctionName("LENGTH") +} + +/// Returns an expression that evaluates the `LENGTH` SQL function. +/// +/// // LENGTH(name) +/// length(Column("name")) +public func length(_ value: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionFunction(.length, arguments: value) +} + + +// MARK: - MAX(...) + +extension SQLFunctionName { + /// The `MAX` function name + public static let max = SQLFunctionName("MAX") +} + +/// Returns an expression that evaluates the `MAX` SQL function. +/// +/// // MAX(score) +/// max(Column("score")) +public func max(_ value: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionFunction(.max, arguments: value) +} + + +// MARK: - MIN(...) + +extension SQLFunctionName { + /// The `MIN` function name + public static let min = SQLFunctionName("MIN") +} + +/// Returns an expression that evaluates the `MIN` SQL function. +/// +/// // MIN(score) +/// min(Column("score")) +public func min(_ value: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionFunction(.min, arguments: value) +} + + +// MARK: - SUM(...) + +extension SQLFunctionName { + /// The `SUM` function name + public static let sum = SQLFunctionName("SUM") +} + +/// Returns an expression that evaluates the `SUM` SQL function. +/// +/// // SUM(amount) +/// sum(Column("amount")) +public func sum(_ value: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionFunction(.sum, arguments: value) +} + + +// MARK: - Swift String functions + +extension SQLSpecificExpressible { + /// Returns an SQL expression that applies the Swift's built-in + /// capitalized String property. It is NULL for non-String arguments. + /// + /// let nameColumn = Column("name") + /// let request = Person.select(nameColumn.capitalized) + /// let names = String.fetchAll(dbQueue, request) // [String] + public var capitalized: SQLExpression { + return DatabaseFunction.capitalize.apply(sqlExpression) + } + + /// Returns an SQL expression that applies the Swift's built-in + /// lowercased String property. It is NULL for non-String arguments. + /// + /// let nameColumn = Column("name") + /// let request = Person.select(nameColumn.lowercased()) + /// let names = String.fetchAll(dbQueue, request) // [String] + public var lowercased: SQLExpression { + return DatabaseFunction.lowercase.apply(sqlExpression) + } + + /// Returns an SQL expression that applies the Swift's built-in + /// uppercased String property. It is NULL for non-String arguments. + /// + /// let nameColumn = Column("name") + /// let request = Person.select(nameColumn.uppercased()) + /// let names = String.fetchAll(dbQueue, request) // [String] + public var uppercased: SQLExpression { + return DatabaseFunction.uppercase.apply(sqlExpression) + } +} + +@available(iOS 9.0, OSX 10.11, *) +extension SQLSpecificExpressible { + /// Returns an SQL expression that applies the Swift's built-in + /// localizedCapitalized String property. It is NULL for non-String arguments. + /// + /// let nameColumn = Column("name") + /// let request = Person.select(nameColumn.localizedCapitalized) + /// let names = String.fetchAll(dbQueue, request) // [String] + public var localizedCapitalized: SQLExpression { + return DatabaseFunction.localizedCapitalize.apply(sqlExpression) + } + + /// Returns an SQL expression that applies the Swift's built-in + /// localizedLowercased String property. It is NULL for non-String arguments. + /// + /// let nameColumn = Column("name") + /// let request = Person.select(nameColumn.localizedLowercased) + /// let names = String.fetchAll(dbQueue, request) // [String] + public var localizedLowercased: SQLExpression { + return DatabaseFunction.localizedLowercase.apply(sqlExpression) + } + + /// Returns an SQL expression that applies the Swift's built-in + /// localizedUppercased String property. It is NULL for non-String arguments. + /// + /// let nameColumn = Column("name") + /// let request = Person.select(nameColumn.localizedUppercased) + /// let names = String.fetchAll(dbQueue, request) // [String] + public var localizedUppercased: SQLExpression { + return DatabaseFunction.localizedUppercase.apply(sqlExpression) + } +} diff --git a/GRDB/QueryInterface/Support/SQLOperators.swift b/GRDB/QueryInterface/Support/SQLOperators.swift new file mode 100644 index 000000000..8609bf46a --- /dev/null +++ b/GRDB/QueryInterface/Support/SQLOperators.swift @@ -0,0 +1,785 @@ +// MARK: - Egality and Identity Operators (=, <>, IS, IS NOT) + +extension SQLBinaryOperator { + /// The `=` binary operator + static let equal = SQLBinaryOperator("=", negated: "<>") + + /// The `<>` binary operator + static let notEqual = SQLBinaryOperator("<>", negated: "=") + + /// The `IS` binary operator + static let `is` = SQLBinaryOperator("IS", negated: "IS NOT") + + /// The `IS NOT` binary operator + static let isNot = SQLBinaryOperator("IS NOT", negated: "IS") +} + +/// An SQL expression that compares two expressions with the `=` SQL operator. +/// +/// // name = 'Arthur' +/// Column("name") == "Arthur" +/// +/// When the right operand is nil, `IS NULL` is used instead. +/// +/// // name IS NULL +/// Column("name") == nil +public func == (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { + if let rhs = rhs { + return SQLExpressionBinary(.equal, lhs.sqlExpression, rhs.sqlExpression) + } else { + return SQLExpressionBinary(.`is`, lhs.sqlExpression, DatabaseValue.null) + } +} + +/// An SQL expression that compares two expressions with the `=` SQL operator. +/// +/// // name = 'Arthur' COLLATE NOCASE +/// Column("name").collating(.nocase) == "Arthur" +/// +/// When the right operand is nil, `IS NULL` is used instead. +/// +/// // name IS NULL +/// Column("name").collating(.nocase) == nil +public func == (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression { + return SQLExpressionCollate(lhs.expression == rhs, collationName: lhs.collationName) +} + +/// An SQL expression that checks the boolean value of an expression. +/// +/// The comparison is done with the built-in boolean evaluation of SQLite: +/// +/// // validated +/// Column("validated") == true +/// +/// // NOT validated +/// Column("validated") == false +public func == (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression { + if rhs { + return lhs.sqlExpression + } else { + return lhs.sqlExpression.negated + } +} + +/// An SQL expression that compares two expressions with the `=` SQL operator. +/// +/// // 'Arthur' = name +/// "Arthur" == Column("name") +/// +/// When the left operand is nil, `IS NULL` is used instead. +/// +/// // name IS NULL +/// nil == Column("name") +public func == (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { + if let lhs = lhs { + return SQLExpressionBinary(.equal, lhs.sqlExpression, rhs.sqlExpression) + } else { + return SQLExpressionBinary(.`is`, rhs.sqlExpression, DatabaseValue.null) + } +} + +/// An SQL expression that compares two expressions with the `=` SQL operator. +/// +/// // 'Arthur' = name COLLATE NOCASE +/// "Arthur" == Column("name").collating(.nocase) +/// +/// When the left operand is nil, `IS NULL` is used instead. +/// +/// // name IS NULL +/// nil == Column("name").collating(.nocase) +public func == (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression { + return SQLExpressionCollate(lhs == rhs.expression, collationName: rhs.collationName) +} + +/// An SQL expression that checks the boolean value of an expression. +/// +/// The comparison is done with the built-in boolean evaluation of SQLite: +/// +/// // validated +/// true == Column("validated") +/// +/// // NOT validated +/// false == Column("validated") +public func == (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression { + if lhs { + return rhs.sqlExpression + } else { + return rhs.sqlExpression.negated + } +} + +/// An SQL expression that compares two expressions with the `=` SQL operator. +/// +/// // email = login +/// Column("email") == Column("login") +public func == (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.equal, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL expression that compares two expressions with the `<>` SQL operator. +/// +/// // name <> 'Arthur' +/// Column("name") != "Arthur" +/// +/// When the right operand is nil, `IS NOT NULL` is used instead. +/// +/// // name IS NOT NULL +/// Column("name") != nil +public func != (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { + if let rhs = rhs { + return SQLExpressionBinary(.notEqual, lhs.sqlExpression, rhs.sqlExpression) + } else { + return SQLExpressionBinary(.isNot, lhs.sqlExpression, DatabaseValue.null) + } +} + +/// An SQL expression that compares two expressions with the `<>` SQL operator. +/// +/// // name <> 'Arthur' COLLATE NOCASE +/// Column("name").collating(.nocase) != "Arthur" +/// +/// When the right operand is nil, `IS NOT NULL` is used instead. +/// +/// // name IS NOT NULL +/// Column("name").collating(.nocase) != nil +public func != (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression { + return SQLExpressionCollate(lhs.expression != rhs, collationName: lhs.collationName) +} + +/// An SQL expression that checks the boolean value of an expression. +/// +/// The comparison is done with the built-in boolean evaluation of SQLite: +/// +/// // NOT validated +/// Column("validated") != true +/// +/// // validated +/// Column("validated") != false +public func != (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression { + if rhs { + return lhs.sqlExpression.negated + } else { + return lhs.sqlExpression + } +} + +/// An SQL expression that compares two expressions with the `<>` SQL operator. +/// +/// // 'Arthur' <> name +/// "Arthur" != Column("name") +/// +/// When the left operand is nil, `IS NOT NULL` is used instead. +/// +/// // name IS NOT NULL +/// nil != Column("name") +public func != (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { + if let lhs = lhs { + return SQLExpressionBinary(.notEqual, lhs.sqlExpression, rhs.sqlExpression) + } else { + return SQLExpressionBinary(.isNot, rhs.sqlExpression, DatabaseValue.null) + } +} + +/// An SQL expression that compares two expressions with the `<>` SQL operator. +/// +/// // 'Arthur' <> name COLLATE NOCASE +/// "Arthur" != Column("name").collating(.nocase) +/// +/// When the left operand is nil, `IS NOT NULL` is used instead. +/// +/// // name IS NOT NULL +/// nil != Column("name").collating(.nocase) +public func != (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression { + return SQLExpressionCollate(lhs != rhs.expression, collationName: rhs.collationName) +} + +/// An SQL expression that checks the boolean value of an expression. +/// +/// The comparison is done with the built-in boolean evaluation of SQLite: +/// +/// // NOT validated +/// true != Column("validated") +/// +/// // validated +/// false != Column("validated") +public func != (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression { + if lhs { + return rhs.sqlExpression.negated + } else { + return rhs.sqlExpression + } +} + +/// An SQL expression that compares two expressions with the `<>` SQL operator. +/// +/// // email <> login +/// Column("email") != Column("login") +public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.notEqual, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL expression that compares two expressions with the `IS` SQL operator. +/// +/// // name IS 'Arthur' +/// Column("name") === "Arthur" +public func === (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { + return SQLExpressionBinary(.`is`, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null) +} + +/// An SQL expression that compares two expressions with the `IS` SQL operator. +/// +/// // name IS 'Arthur' COLLATE NOCASE +/// Column("name").collating(.nocase) === "Arthur" +public func === (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression { + return SQLExpressionCollate(lhs.expression === rhs, collationName: lhs.collationName) +} + +/// An SQL expression that compares two expressions with the `IS` SQL operator. +/// +/// // name IS 'Arthur' +/// "Arthur" === Column("name") +public func === (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { + if let lhs = lhs { + return SQLExpressionBinary(.`is`, lhs.sqlExpression, rhs.sqlExpression) + } else { + return SQLExpressionBinary(.`is`, rhs.sqlExpression, DatabaseValue.null) + } +} + +/// An SQL expression that compares two expressions with the `IS` SQL operator. +/// +/// // name IS 'Arthur' COLLATE NOCASE +/// "Arthur" === Column("name").collating(.nocase) +public func === (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression { + return SQLExpressionCollate(lhs == rhs.expression, collationName: rhs.collationName) +} + +/// An SQL expression that compares two expressions with the `IS` SQL operator. +/// +/// // email IS login +/// Column("email") === Column("login") +public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.`is`, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL expression that compares two expressions with the `IS NOT` SQL operator. +/// +/// // name IS NOT 'Arthur' +/// Column("name") !== "Arthur" +public func !== (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { + return SQLExpressionBinary(.isNot, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null) +} + +/// An SQL expression that compares two expressions with the `IS NOT` SQL operator. +/// +/// // name IS NOT 'Arthur' COLLATE NOCASE +/// Column("name").collating(.nocase) !== "Arthur" +public func !== (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression { + return SQLExpressionCollate(lhs.expression !== rhs, collationName: lhs.collationName) +} + +/// An SQL expression that compares two expressions with the `IS NOT` SQL operator. +/// +/// // name IS NOT 'Arthur' +/// "Arthur" !== Column("name") +public func !== (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { + if let lhs = lhs { + return SQLExpressionBinary(.isNot, lhs.sqlExpression, rhs.sqlExpression) + } else { + return SQLExpressionBinary(.isNot, rhs.sqlExpression, DatabaseValue.null) + } +} + +/// An SQL expression that compares two expressions with the `IS NOT` SQL operator. +/// +/// // name IS NOT 'Arthur' COLLATE NOCASE +/// "Arthur" !== Column("name").collating(.nocase) +public func !== (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression { + return SQLExpressionCollate(lhs !== rhs.expression, collationName: rhs.collationName) +} + +/// An SQL expression that compares two expressions with the `IS NOT` SQL operator. +/// +/// // email IS NOT login +/// Column("email") !== Column("login") +public func !== (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.isNot, lhs.sqlExpression, rhs.sqlExpression) +} + + +// MARK: - Comparison Operators (<, >, <=, >=) + +extension SQLBinaryOperator { + /// The `<` binary operator + static let lessThan = SQLBinaryOperator("<") + + /// The `<=` binary operator + static let lessThanOrEqual = SQLBinaryOperator("<=") + + /// The `>` binary operator + static let greaterThan = SQLBinaryOperator(">") + + /// The `>=` binary operator + static let greaterThanOrEqual = SQLBinaryOperator(">=") +} + +/// An SQL expression that compares two expressions with the `<` SQL operator. +/// +/// // age < 18 +/// Column("age") < 18 +public func < (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { + return SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL expression that compares two expressions with the `<` SQL operator. +/// +/// // name < 'Arthur' COLLATE NOCASE +/// Column("name").collating(.nocase) < "Arthur" +public func < (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression { + return SQLExpressionCollate(lhs.expression < rhs, collationName: lhs.collationName) +} + +/// An SQL expression that compares two expressions with the `<` SQL operator. +/// +/// // 18 < age +/// 18 < Column("age") +public func < (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL expression that compares two expressions with the `<` SQL operator. +/// +/// // 'Arthur' < name COLLATE NOCASE +/// "Arthur" < Column("name").collating(.nocase) +public func < (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression { + return SQLExpressionCollate(lhs < rhs.expression, collationName: rhs.collationName) +} + +/// An SQL expression that compares two expressions with the `<` SQL operator. +/// +/// // width < height +/// Column("width") < Column("height") +public func < (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL expression that compares two expressions with the `<=` SQL operator. +/// +/// // age <= 18 +/// Column("age") <= 18 +public func <= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { + return SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL expression that compares two expressions with the `<=` SQL operator. +/// +/// // name <= 'Arthur' COLLATE NOCASE +/// Column("name").collating(.nocase) <= "Arthur" +public func <= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression { + return SQLExpressionCollate(lhs.expression <= rhs, collationName: lhs.collationName) +} + +/// An SQL expression that compares two expressions with the `<=` SQL operator. +/// +/// // 18 <= age +/// 18 <= Column("age") +public func <= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL expression that compares two expressions with the `<=` SQL operator. +/// +/// // 'Arthur' <= name COLLATE NOCASE +/// "Arthur" <= Column("name").collating(.nocase) +public func <= (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression { + return SQLExpressionCollate(lhs <= rhs.expression, collationName: rhs.collationName) +} + +/// An SQL expression that compares two expressions with the `<=` SQL operator. +/// +/// // width <= height +/// Column("width") <= Column("height") +public func <= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL expression that compares two expressions with the `>` SQL operator. +/// +/// // age > 18 +/// Column("age") > 18 +public func > (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { + return SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL expression that compares two expressions with the `>` SQL operator. +/// +/// // age > 'Arthur' COLLATE NOCASE +/// Column("name").collating(.nocase) > "Arthur" +public func > (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression { + return SQLExpressionCollate(lhs.expression > rhs, collationName: lhs.collationName) +} + +/// An SQL expression that compares two expressions with the `>` SQL operator. +/// +/// // 18 > age +/// 18 > Column("age") +public func > (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL expression that compares two expressions with the `>` SQL operator. +/// +/// // 'Arthur' > name COLLATE NOCASE +/// "Arthur" > Column("name").collating(.nocase) +public func > (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression { + return SQLExpressionCollate(lhs > rhs.expression, collationName: rhs.collationName) +} + +/// An SQL expression that compares two expressions with the `>` SQL operator. +/// +/// // width > height +/// Column("width") > Column("height") +public func > (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL expression that compares two expressions with the `>=` SQL operator. +/// +/// // age >= 18 +/// Column("age") >= 18 +public func >= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { + return SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL expression that compares two expressions with the `>=` SQL operator. +/// +/// // name >= 'Arthur' COLLATE NOCASE +/// Column("name").collating(.nocase) >= "Arthur" +public func >= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression { + return SQLExpressionCollate(lhs.expression >= rhs, collationName: lhs.collationName) +} + +/// An SQL expression that compares two expressions with the `>=` SQL operator. +/// +/// // 18 >= age +/// 18 >= Column("age") +public func >= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL expression that compares two expressions with the `>=` SQL operator. +/// +/// // 'Arthur' >= age COLLATE NOCASE +/// "Arthur" >= Column("age").collating(.nocase) +public func >= (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression { + return SQLExpressionCollate(lhs >= rhs.expression, collationName: rhs.collationName) +} + +/// An SQL expression that compares two expressions with the `>=` SQL operator. +/// +/// // width >= height +/// Column("width") >= Column("height") +public func >= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) +} + + +// MARK: - Inclusion Operators (BETWEEN, IN) + +extension Range where Bound: SQLExpressible { + /// An SQL expression that checks the inclusion of an expression in a range. + /// + /// // email >= 'A' AND email < 'B' + /// ("A"..<"B").contains(Column("email")) + public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { + return (element >= lowerBound) && (element < upperBound) + } + + /// An SQL expression that checks the inclusion of an expression in a range. + /// + /// // email >= 'A' COLLATE NOCASE AND email < 'B' COLLATE NOCASE + /// ("A"..<"B").contains(Column("email").collating(.nocase)) + public func contains(_ element: SQLCollatedExpression) -> SQLExpression { + return (element >= lowerBound) && (element < upperBound) + } +} + +extension ClosedRange where Bound: SQLExpressible { + /// An SQL expression that checks the inclusion of an expression in a range. + /// + /// // email BETWEEN 'A' AND 'B' + /// ("A"..."B").contains(Column("email")) + public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBetween(element.sqlExpression, lowerBound.sqlExpression, upperBound.sqlExpression) + } + + /// An SQL expression that checks the inclusion of an expression in a range. + /// + /// // email BETWEEN 'A' AND 'B' COLLATE NOCASE + /// ("A"..."B").contains(Column("email").collating(.nocase)) + public func contains(_ element: SQLCollatedExpression) -> SQLExpression { + return SQLExpressionCollate(contains(element.expression), collationName: element.collationName) + } +} + +extension CountableRange where Bound: SQLExpressible { + /// An SQL expression that checks the inclusion of an expression in a range. + /// + /// // id BETWEEN 1 AND 9 + /// (1..<10).contains(Column("id")) + public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBetween(element.sqlExpression, lowerBound.sqlExpression, upperBound.advanced(by: -1).sqlExpression) + } +} + +extension CountableClosedRange where Bound: SQLExpressible { + /// An SQL expression that checks the inclusion of an expression in a range. + /// + /// // id BETWEEN 1 AND 10 + /// (1...10).contains(Column("id")) + public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBetween(element.sqlExpression, lowerBound.sqlExpression, upperBound.sqlExpression) + } +} + +extension Sequence where Self.Iterator.Element: SQLExpressible { + /// An SQL expression that checks the inclusion of an expression in + /// a sequence. + /// + /// // id IN (1,2,3) + /// [1, 2, 3].contains(Column("id")) + public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionsArray(self).contains(element.sqlExpression) + } + + /// An SQL expression that checks the inclusion of an expression in + /// a sequence. + /// + /// // name IN ('A', 'B') COLLATE NOCASE + /// ["A", "B"].contains(Column("name").collating(.nocase)) + public func contains(_ element: SQLCollatedExpression) -> SQLExpression { + return SQLExpressionCollate(contains(element.expression), collationName: element.collationName) + } +} + + +// MARK: - Arithmetic Operators (+, -, *, /) + +extension SQLBinaryOperator { + /// The `+` binary operator + static let plus = SQLBinaryOperator("+") + + /// The `-` binary operator + static let minus = SQLBinaryOperator("-") + + /// The `*` binary operator + static let multiply = SQLBinaryOperator("*") + + /// The `/` binary operator + static let divide = SQLBinaryOperator("/") +} + +extension SQLUnaryOperator { + /// The `-` unary operator + public static let minus = SQLUnaryOperator("-", needsRightSpace: false) +} + +/// An SQL arithmetic multiplication. +/// +/// // width * 2 +/// Column("width") * 2 +public func * (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { + return SQLExpressionBinary(.multiply, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL arithmetic multiplication. +/// +/// // 2 * width +/// 2 * Column("width") +public func * (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.multiply, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL arithmetic multiplication. +/// +/// // width * height +/// Column("width") * Column("height") +public func * (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.multiply, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL arithmetic division. +/// +/// // width / 2 +/// Column("width") / 2 +public func / (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { + return SQLExpressionBinary(.divide, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL arithmetic division. +/// +/// // 2 / width +/// 2 / Column("width") +public func / (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.divide, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL arithmetic division. +/// +/// // width / height +/// Column("width") / Column("height") +public func / (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.divide, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL arithmetic addition. +/// +/// // width + 2 +/// Column("width") + 2 +public func + (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { + return SQLExpressionBinary(.plus, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL arithmetic addition. +/// +/// // 2 + width +/// 2 + Column("width") +public func + (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.plus, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL arithmetic addition. +/// +/// // width + height +/// Column("width") + Column("height") +public func + (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.plus, lhs.sqlExpression, rhs.sqlExpression) +} + +/// A negated SQL arithmetic expression. +/// +/// // -width +/// -Column("width") +public prefix func - (value: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionUnary(.minus, value.sqlExpression) +} + +/// An SQL arithmetic substraction. +/// +/// // width - 2 +/// Column("width") - 2 +public func - (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { + return SQLExpressionBinary(.minus, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL arithmetic substraction. +/// +/// // 2 - width +/// 2 - Column("width") +public func - (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.minus, lhs.sqlExpression, rhs.sqlExpression) +} + +/// An SQL arithmetic substraction. +/// +/// // width - height +/// Column("width") - Column("height") +public func - (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.minus, lhs.sqlExpression, rhs.sqlExpression) +} + + +// MARK: - Logical Operators (AND, OR, NOT) + +extension SQLBinaryOperator { + /// The `AND` binary operator + static let and = SQLBinaryOperator("AND") + + /// The `OR` binary operator + static let or = SQLBinaryOperator("OR") +} + +extension SQLUnaryOperator { + /// The `NOT` unary operator + public static let not = SQLUnaryOperator("NOT", needsRightSpace: true) +} + +/// A logical SQL expression with the `AND` SQL operator. +/// +/// // favorite AND 0 +/// Column("favorite") && false +public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { + return SQLExpressionBinary(.and, lhs.sqlExpression, rhs.sqlExpression) +} + +/// A logical SQL expression with the `AND` SQL operator. +/// +/// // 0 AND favorite +/// false && Column("favorite") +public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.and, lhs.sqlExpression, rhs.sqlExpression) +} + +/// A logical SQL expression with the `AND` SQL operator. +/// +/// // email IS NOT NULL AND favorite +/// Column("email") != nil && Column("favorite") +public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.and, lhs.sqlExpression, rhs.sqlExpression) +} + +/// A logical SQL expression with the `OR` SQL operator. +/// +/// // favorite OR 1 +/// Column("favorite") || true +public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { + return SQLExpressionBinary(.or, lhs.sqlExpression, rhs.sqlExpression) +} + +/// A logical SQL expression with the `OR` SQL operator. +/// +/// // 0 OR favorite +/// true || Column("favorite") +public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.or, lhs.sqlExpression, rhs.sqlExpression) +} + +/// A logical SQL expression with the `OR` SQL operator. +/// +/// // email IS NULL OR hidden +/// Column("email") == nil || Column("hidden") +public func || (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { + return SQLExpressionBinary(.or, lhs.sqlExpression, rhs.sqlExpression) +} + +/// A negated logical SQL expression with the `NOT` SQL operator. +/// +/// // NOT hidden +/// !Column("hidden") +/// +/// Some expressions may be negated with specific SQL operators: +/// +/// // id NOT BETWEEN 1 AND 10 +/// !((1...10).contains(Column("id"))) +public prefix func ! (value: SQLSpecificExpressible) -> SQLExpression { + return value.sqlExpression.negated +} + + +// MARK: - Like Operator + +extension SQLBinaryOperator { + /// The `LIKE` binary operator + static let like = SQLBinaryOperator("LIKE") +} + +extension SQLSpecificExpressible { + + /// An SQL expression with the `LIKE` SQL operator. + /// + /// // email LIKE '%@example.com" + /// Column("email").like("%@example.com") + public func like(_ pattern: SQLExpressible) -> SQLExpression { + return SQLExpressionBinary(.like, self, pattern) + } +} diff --git a/GRDB/QueryInterface/SQLTableBuilder.swift b/GRDB/QueryInterface/TableDefinition.swift similarity index 88% rename from GRDB/QueryInterface/SQLTableBuilder.swift rename to GRDB/QueryInterface/TableDefinition.swift index d4a34d179..17c6cdb9d 100644 --- a/GRDB/QueryInterface/SQLTableBuilder.swift +++ b/GRDB/QueryInterface/TableDefinition.swift @@ -141,7 +141,7 @@ extension Database { /// /// See https://www.sqlite.org/lang_createtable.html public final class TableDefinition { - private typealias KeyConstraint = (columns: [String], conflictResolution: SQLConflictResolution?) + private typealias KeyConstraint = (columns: [String], conflictResolution: Database.ConflictResolution?) private let name: String private let temporary: Bool @@ -150,8 +150,8 @@ public final class TableDefinition { private var columns: [ColumnDefinition] = [] private var primaryKeyConstraint: KeyConstraint? private var uniqueKeyConstraints: [KeyConstraint] = [] - private var foreignKeyConstraints: [(columns: [String], table: String, destinationColumns: [String]?, deleteAction: SQLForeignKeyAction?, updateAction: SQLForeignKeyAction?, deferred: Bool)] = [] - private var checkConstraints: [_SQLExpression] = [] + private var foreignKeyConstraints: [(columns: [String], table: String, destinationColumns: [String]?, deleteAction: Database.ForeignKeyAction?, updateAction: Database.ForeignKeyAction?, deferred: Bool)] = [] + private var checkConstraints: [SQLExpression] = [] init(name: String, temporary: Bool, ifNotExists: Bool, withoutRowID: Bool) { self.name = name @@ -172,7 +172,7 @@ public final class TableDefinition { /// - parameter type: the column type. /// - returns: An ColumnDefinition that allows you to refine the /// column definition. - @discardableResult public func column(_ name: String, _ type: SQLColumnType) -> ColumnDefinition { + @discardableResult public func column(_ name: String, _ type: Database.ColumnType) -> ColumnDefinition { let column = ColumnDefinition(name: name, type: type) columns.append(column) return column @@ -192,7 +192,7 @@ public final class TableDefinition { /// - parameter columns: The primary key columns. /// - parameter conflitResolution: An optional conflict resolution /// (see https://www.sqlite.org/lang_conflict.html). - public func primaryKey(_ columns: [String], onConflict conflictResolution: SQLConflictResolution? = nil) { + public func primaryKey(_ columns: [String], onConflict conflictResolution: Database.ConflictResolution? = nil) { guard primaryKeyConstraint == nil else { fatalError("can't define several primary keys") } @@ -212,7 +212,7 @@ public final class TableDefinition { /// - parameter columns: The unique key columns. /// - parameter conflitResolution: An optional conflict resolution /// (see https://www.sqlite.org/lang_conflict.html). - public func uniqueKey(_ columns: [String], onConflict conflictResolution: SQLConflictResolution? = nil) { + public func uniqueKey(_ columns: [String], onConflict conflictResolution: Database.ConflictResolution? = nil) { uniqueKeyConstraints.append((columns: columns, conflictResolution: conflictResolution)) } @@ -237,7 +237,7 @@ public final class TableDefinition { /// - updateAction: Optional action when the referenced row is updated. /// - deferred: If true, defines a deferred foreign key constraint. /// See https://www.sqlite.org/foreignkeys.html#fk_deferred. - public func foreignKey(_ columns: [String], references table: String, columns destinationColumns: [String]? = nil, onDelete deleteAction: SQLForeignKeyAction? = nil, onUpdate updateAction: SQLForeignKeyAction? = nil, deferred: Bool = false) { + public func foreignKey(_ columns: [String], references table: String, columns destinationColumns: [String]? = nil, onDelete deleteAction: Database.ForeignKeyAction? = nil, onUpdate updateAction: Database.ForeignKeyAction? = nil, deferred: Bool = false) { foreignKeyConstraints.append((columns: columns, table: table, destinationColumns: destinationColumns, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred)) } @@ -270,7 +270,7 @@ public final class TableDefinition { /// /// - parameter sql: An SQL snippet public func check(sql: String) { - checkConstraints.append(_SQLExpression.sqlLiteral(sql, nil)) + checkConstraints.append(SQLExpressionLiteral(sql)) } fileprivate func sql(_ db: Database) throws -> String { @@ -351,8 +351,7 @@ public final class TableDefinition { for checkExpression in checkConstraints { var chunks: [String] = [] chunks.append("CHECK") - var arguments: StatementArguments? = nil // nil so that checkExpression.sql(&arguments) embeds literals - chunks.append("(" + checkExpression.sql(&arguments) + ")") + chunks.append("(" + checkExpression.sql + ")") items.append(chunks.joined(separator: " ")) } @@ -396,7 +395,7 @@ public final class TableAlteration { /// - parameter type: the column type. /// - returns: An ColumnDefinition that allows you to refine the /// column definition. - @discardableResult public func add(column name: String, _ type: SQLColumnType) -> ColumnDefinition { + @discardableResult public func add(column name: String, _ type: Database.ColumnType) -> ColumnDefinition { let column = ColumnDefinition(name: name, type: type) addedColumns.append(column) return column @@ -435,16 +434,16 @@ public final class TableAlteration { /// https://www.sqlite.org/lang_altertable.html public final class ColumnDefinition { fileprivate let name: String - private let type: SQLColumnType - fileprivate var primaryKey: (conflictResolution: SQLConflictResolution?, autoincrement: Bool)? - private var notNullConflictResolution: SQLConflictResolution? - private var uniqueConflictResolution: SQLConflictResolution? - private var checkConstraints: [_SQLExpression] = [] - private var foreignKeyConstraints: [(table: String, column: String?, deleteAction: SQLForeignKeyAction?, updateAction: SQLForeignKeyAction?, deferred: Bool)] = [] - private var defaultExpression: _SQLExpression? + private let type: Database.ColumnType + fileprivate var primaryKey: (conflictResolution: Database.ConflictResolution?, autoincrement: Bool)? + private var notNullConflictResolution: Database.ConflictResolution? + private var uniqueConflictResolution: Database.ConflictResolution? + private var checkConstraints: [SQLExpression] = [] + private var foreignKeyConstraints: [(table: String, column: String?, deleteAction: Database.ForeignKeyAction?, updateAction: Database.ForeignKeyAction?, deferred: Bool)] = [] + private var defaultExpression: SQLExpression? private var collationName: String? - init(name: String, type: SQLColumnType) { + init(name: String, type: Database.ColumnType) { self.name = name self.type = type } @@ -463,7 +462,7 @@ public final class ColumnDefinition { /// (see https://www.sqlite.org/lang_conflict.html). /// - autoincrement: If true, the primary key is autoincremented. /// - returns: Self so that you can further refine the column definition. - @discardableResult public func primaryKey(onConflict conflictResolution: SQLConflictResolution? = nil, autoincrement: Bool = false) -> Self { + @discardableResult public func primaryKey(onConflict conflictResolution: Database.ConflictResolution? = nil, autoincrement: Bool = false) -> Self { primaryKey = (conflictResolution: conflictResolution, autoincrement: autoincrement) return self } @@ -479,7 +478,7 @@ public final class ColumnDefinition { /// - parameter conflitResolution: An optional conflict resolution /// (see https://www.sqlite.org/lang_conflict.html). /// - returns: Self so that you can further refine the column definition. - @discardableResult public func notNull(onConflict conflictResolution: SQLConflictResolution? = nil) -> Self { + @discardableResult public func notNull(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self { notNullConflictResolution = conflictResolution ?? .abort return self } @@ -495,7 +494,7 @@ public final class ColumnDefinition { /// - parameter conflitResolution: An optional conflict resolution /// (see https://www.sqlite.org/lang_conflict.html). /// - returns: Self so that you can further refine the column definition. - @discardableResult public func unique(onConflict conflictResolution: SQLConflictResolution? = nil) -> Self { + @discardableResult public func unique(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self { uniqueConflictResolution = conflictResolution ?? .abort return self } @@ -527,7 +526,7 @@ public final class ColumnDefinition { /// - parameter sql: An SQL snippet. /// - returns: Self so that you can further refine the column definition. @discardableResult public func check(sql: String) -> Self { - checkConstraints.append(_SQLExpression.sqlLiteral(sql, nil)) + checkConstraints.append(SQLExpressionLiteral(sql)) return self } @@ -557,7 +556,7 @@ public final class ColumnDefinition { /// - parameter sql: An SQL snippet. /// - returns: Self so that you can further refine the column definition. @discardableResult public func defaults(sql: String) -> Self { - defaultExpression = _SQLExpression.sqlLiteral(sql, nil) + defaultExpression = SQLExpressionLiteral(sql) return self } @@ -569,9 +568,9 @@ public final class ColumnDefinition { /// /// See https://www.sqlite.org/datatype3.html#collation /// - /// - parameter collation: An SQLCollation. + /// - parameter collation: An Database.CollationName. /// - returns: Self so that you can further refine the column definition. - @discardableResult public func collate(_ collation: SQLCollation) -> Self { + @discardableResult public func collate(_ collation: Database.CollationName) -> Self { collationName = collation.rawValue return self } @@ -608,7 +607,7 @@ public final class ColumnDefinition { /// - deferred: If true, defines a deferred foreign key constraint. /// See https://www.sqlite.org/foreignkeys.html#fk_deferred. /// - returns: Self so that you can further refine the column definition. - @discardableResult public func references(_ table: String, column: String? = nil, onDelete deleteAction: SQLForeignKeyAction? = nil, onUpdate updateAction: SQLForeignKeyAction? = nil, deferred: Bool = false) -> Self { + @discardableResult public func references(_ table: String, column: String? = nil, onDelete deleteAction: Database.ForeignKeyAction? = nil, onUpdate updateAction: Database.ForeignKeyAction? = nil, deferred: Bool = false) -> Self { foreignKeyConstraints.append((table: table, column: column, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred)) return self } @@ -651,14 +650,12 @@ public final class ColumnDefinition { for checkConstraint in checkConstraints { chunks.append("CHECK") - var arguments: StatementArguments? = nil // nil so that checkConstraint.sql(&arguments) embeds literals - chunks.append("(" + checkConstraint.sql(&arguments) + ")") + chunks.append("(" + checkConstraint.sql + ")") } if let defaultExpression = defaultExpression { - var arguments: StatementArguments? = nil // nil so that defaultExpression.sql(&arguments) embeds literals chunks.append("DEFAULT") - chunks.append(defaultExpression.sql(&arguments)) + chunks.append(defaultExpression.sql) } if let collationName = collationName { @@ -700,7 +697,7 @@ private struct IndexDefinition { let columns: [String] let unique: Bool let ifNotExists: Bool - let condition: _SQLExpression? + let condition: SQLExpression? func sql() -> String { var chunks: [String] = [] @@ -717,58 +714,8 @@ private struct IndexDefinition { chunks.append("\(table.quotedDatabaseIdentifier)(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") if let condition = condition { chunks.append("WHERE") - var arguments: StatementArguments? = nil // nil so that condition.sql(&arguments) embeds literals - chunks.append(condition.sql(&arguments)) + chunks.append(condition.sql) } return chunks.joined(separator: " ") } } - -/// A built-in SQLite collation. -/// -/// See https://www.sqlite.org/datatype3.html#collation -public enum SQLCollation : String { - case binary = "BINARY" - case nocase = "NOCASE" - case rtrim = "RTRIM" -} - -/// An SQLite conflict resolution. -/// -/// See https://www.sqlite.org/lang_conflict.html. -public enum SQLConflictResolution : String { - case rollback = "ROLLBACK" - case abort = "ABORT" - case fail = "FAIL" - case ignore = "IGNORE" - case replace = "REPLACE" -} - -/// An SQL column type. -/// -/// try db.create(table: "persons") { t in -/// t.column("id", .integer).primaryKey() -/// t.column("title", .text) -/// } -/// -/// See https://www.sqlite.org/datatype3.html -public enum SQLColumnType : String { - case text = "TEXT" - case integer = "INTEGER" - case double = "DOUBLE" - case numeric = "NUMERIC" - case boolean = "BOOLEAN" - case blob = "BLOB" - case date = "DATE" - case datetime = "DATETIME" -} - -/// A foreign key action. -/// -/// See https://www.sqlite.org/foreignkeys.html -public enum SQLForeignKeyAction : String { - case cascade = "CASCADE" - case restrict = "RESTRICT" - case setNull = "SET NULL" - case setDefault = "SET DEFAULT" -} diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/Persistable.swift index 10e8465c4..3e0cde56c 100644 --- a/GRDB/Record/Persistable.swift +++ b/GRDB/Record/Persistable.swift @@ -44,13 +44,13 @@ private func databaseValues(for columns: [String], inDictionary dictionary: [Str /// See https://www.sqlite.org/lang_conflict.html public struct PersistenceConflictPolicy { /// The conflict resolution algorithm for insertions - public let conflictResolutionForInsert: SQLConflictResolution + public let conflictResolutionForInsert: Database.ConflictResolution /// The conflict resolution algorithm for updates - public let conflictResolutionForUpdate: SQLConflictResolution + public let conflictResolutionForUpdate: Database.ConflictResolution /// Creates a policy - public init(insert: SQLConflictResolution = .abort, update: SQLConflictResolution = .abort) { + public init(insert: Database.ConflictResolution = .abort, update: Database.ConflictResolution = .abort) { self.conflictResolutionForInsert = insert self.conflictResolutionForUpdate = update } @@ -414,7 +414,7 @@ public extension MutablePersistable { } -extension SQLConflictResolution { +extension Database.ConflictResolution { var invalidatesLastInsertedRowID: Bool { switch self { case .abort, .fail, .rollback, .replace: @@ -606,7 +606,7 @@ final class DAO { self.primaryKey = primaryKey } - func insertStatement(onConflict: SQLConflictResolution) -> UpdateStatement { + func insertStatement(onConflict: Database.ConflictResolution) -> UpdateStatement { let query = InsertQuery( onConflict: onConflict, tableName: databaseTableName, @@ -617,7 +617,7 @@ final class DAO { } /// Returns nil if and only if primary key is nil - func updateStatement(columns: Set, onConflict: SQLConflictResolution) -> UpdateStatement? { + func updateStatement(columns: Set, onConflict: Database.ConflictResolution) -> UpdateStatement? { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey?.columns ?? [] let primaryKeyValues = databaseValues(for: primaryKeyColumns, inDictionary: persistentDictionary) @@ -693,7 +693,7 @@ final class DAO { // MARK: - InsertQuery private struct InsertQuery { - let onConflict: SQLConflictResolution + let onConflict: Database.ConflictResolution let tableName: String let insertedColumns: [String] } @@ -732,7 +732,7 @@ extension InsertQuery { // MARK: - UpdateQuery private struct UpdateQuery { - let onConflict: SQLConflictResolution + let onConflict: Database.ConflictResolution let tableName: String let updatedColumns: [String] let conditionColumns: [String] diff --git a/Playgrounds/MyPlayground.playground/Contents.swift b/Playgrounds/MyPlayground.playground/Contents.swift index a0161407e..5c7babf5b 100644 --- a/Playgrounds/MyPlayground.playground/Contents.swift +++ b/Playgrounds/MyPlayground.playground/Contents.swift @@ -2,14 +2,20 @@ import GRDB -let path = "/tmp/database.sqlite" + var configuration = Configuration() configuration.trace = { print($0) } -let dbQueue = try! DatabaseQueue(path: path, configuration: configuration) +let dbQueue = DatabaseQueue(configuration: configuration) try! dbQueue.inDatabase { db in - try db.create(table: "persons", ifNotExists: true) { t in + try db.create(table: "persons") { t in t.column("id", .integer).primaryKey() t.column("name", .text) } + + try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Arthur"]) + try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Barbara"]) + + let names = String.fetchAll(db, "SELECT name FROM persons") + print(names) } diff --git a/README.md b/README.md index 9f68938e6..70c40ebe5 100644 --- a/README.md +++ b/README.md @@ -247,7 +247,7 @@ github "groue/GRDB.swift" 1. Download a copy of GRDB.swift. 2. Embed the `GRDB.xcodeproj` project in your own project. 3. Add the `GRDBOSX`, `GRDBiOS`, or `GRDBWatchOS` target in the **Target Dependencies** section of the **Build Phases** tab of your application target. -4. Add the the `GRDB.framework` from the targetted platform to the **Embedded Binaries** section of the **General** tab of your target. +4. Add the `GRDB.framework` from the targetted platform to the **Embedded Binaries** section of the **General** tab of your target. See [GRDBDemoiOS](DemoApps/GRDBDemoiOS) for an example of such integration. @@ -336,8 +336,9 @@ If you do otherwise, you may well experience concurrency issues, and you don't w ```swift var config = Configuration() config.readonly = true -config.foreignKeysEnabled = true // The default is already true +config.foreignKeysEnabled = true // Default is already true config.trace = { print($0) } // Prints all SQL statements +config.textEncoding = .utf8 // Default is already UTF-8 config.fileAttributes = [FileAttributeKey.protectionKey.rawValue: ...] // Configure database protection let dbQueue = try DatabaseQueue( @@ -415,8 +416,9 @@ See [Concurrency](#concurrency) for more information. ```swift var config = Configuration() config.readonly = true -config.foreignKeysEnabled = true // The default is already true +config.foreignKeysEnabled = true // Default is already true config.trace = { print($0) } // Prints all SQL statements +config.textEncoding = .utf8 // Default is already UTF-8 config.fileAttributes = [FileAttributeKey.protectionKey.rawValue: ...] // Configure database protection config.maximumReaderCount = 10 // The default is 5 @@ -888,7 +890,7 @@ class Link : Record { } override var persistentDictionary: [String: DatabaseValueConvertible?] { - return ["url": url, "verified": verified] + return ["url": url, "verified": isVerified] } } ``` diff --git a/Support/GRDB-0-84-0-ConversionHelper.swift b/Support/GRDB-0-84-0-ConversionHelper.swift new file mode 100644 index 000000000..5b6ff6113 --- /dev/null +++ b/Support/GRDB-0-84-0-ConversionHelper.swift @@ -0,0 +1,29 @@ +// +// GRDB-Swift2-ConversionHelper.swift +// GRDB +// +// Created by Swiftlyfalling. +// +// Provides automatic renaming Fix-Its for many of the Swift 2.x -> Swift 3 GRDB API changes. +// Consult the CHANGELOG.md and documentation for details on all of the changes. +// + +import Foundation + +@available(*, unavailable, renamed:"Database.ForeignKeyAction") +public typealias SQLForeignKeyAction = Database.ForeignKeyAction + +@available(*, unavailable, renamed:"Database.ColumnType") +public typealias SQLColumnType = Database.ColumnType + +@available(*, unavailable, renamed:"Database.ConflictResolution") +public typealias SQLConflictResolution = Database.ConflictResolution + +@available(*, unavailable, renamed:"Database.CollationName") +public typealias SQLCollation = Database.CollationName + +@available(*, unavailable, renamed:"SQLSpecificExpressible") +public typealias _SpecificSQLExpressible = SQLSpecificExpressible + +@available(*, unavailable, renamed:"SQLExpression") +public typealias _SQLExpression = SQLExpression diff --git a/Support/GRDB-Swift2-ConversionHelper.swift b/Support/GRDB-Swift2-ConversionHelper.swift index 350283c33..0011d1023 100644 --- a/Support/GRDB-Swift2-ConversionHelper.swift +++ b/Support/GRDB-Swift2-ConversionHelper.swift @@ -185,25 +185,25 @@ public typealias TransactionObserverType = TransactionObserver @available(*, unavailable, renamed:"Column") public typealias SQLColumn = Column -extension _SpecificSQLExpressible { +extension SQLSpecificExpressible { @available(*, unavailable, renamed:"capitalized") - public var capitalizedString: _SQLExpression { get { return capitalized } } + public var capitalizedString: SQLExpression { get { return capitalized } } @available(*, unavailable, renamed:"lowercased") - public var lowercaseString: _SQLExpression { get { return lowercased } } + public var lowercaseString: SQLExpression { get { return lowercased } } @available(*, unavailable, renamed:"uppercased") - public var uppercaseString: _SQLExpression { get { return uppercased } } + public var uppercaseString: SQLExpression { get { return uppercased } } } @available(iOS 9.0, OSX 10.11, *) -extension _SpecificSQLExpressible { +extension SQLSpecificExpressible { @available(*, unavailable, renamed:"localizedCapitalized") - public var localizedCapitalizedString: _SQLExpression { get { return localizedCapitalized } } + public var localizedCapitalizedString: SQLExpression { get { return localizedCapitalized } } @available(*, unavailable, renamed:"localizedLowercased") - public var localizedLowercaseString: _SQLExpression { get { return localizedLowercased } } + public var localizedLowercaseString: SQLExpression { get { return localizedLowercased } } @available(*, unavailable, renamed:"localizedUppercased") - public var localizedUppercaseString: _SQLExpression { get { return localizedUppercased } } + public var localizedUppercaseString: SQLExpression { get { return localizedUppercased } } } diff --git a/Tests/Private/DatabaseValueConvertibleEscapingTests.swift b/Tests/Private/DatabaseValueConvertibleEscapingTests.swift index 9208af344..02efabd1f 100644 --- a/Tests/Private/DatabaseValueConvertibleEscapingTests.swift +++ b/Tests/Private/DatabaseValueConvertibleEscapingTests.swift @@ -11,27 +11,27 @@ import XCTest class DatabaseValueConvertibleEscapingTests: GRDBTestCase { func testText() { - XCTAssertEqual("".sqlLiteral, "''") - XCTAssertEqual("foo".sqlLiteral, "'foo'") - XCTAssertEqual("\"foo\"".sqlLiteral, "'\"foo\"'") - XCTAssertEqual("'foo'".sqlLiteral, "'''foo'''") + XCTAssertEqual("".databaseValue.sql, "''") + XCTAssertEqual("foo".databaseValue.sql, "'foo'") + XCTAssertEqual("\"foo\"".databaseValue.sql, "'\"foo\"'") + XCTAssertEqual("'foo'".databaseValue.sql, "'''foo'''") } func testInteger() { - XCTAssertEqual(0.sqlLiteral, "0") - XCTAssertEqual(Int64.min.sqlLiteral, "-9223372036854775808") - XCTAssertEqual(Int64.max.sqlLiteral, "9223372036854775807") + XCTAssertEqual(0.databaseValue.sql, "0") + XCTAssertEqual(Int64.min.databaseValue.sql, "-9223372036854775808") + XCTAssertEqual(Int64.max.databaseValue.sql, "9223372036854775807") } func testDouble() { - XCTAssertEqual(0.0.sqlLiteral, "0.0") - XCTAssertEqual(1.0.sqlLiteral, "1.0") - XCTAssertEqual((-1.0).sqlLiteral, "-1.0") - XCTAssertEqual(1.5.sqlLiteral, "1.5") + XCTAssertEqual(0.0.databaseValue.sql, "0.0") + XCTAssertEqual(1.0.databaseValue.sql, "1.0") + XCTAssertEqual((-1.0).databaseValue.sql, "-1.0") + XCTAssertEqual(1.5.databaseValue.sql, "1.5") } func testBlob() { - XCTAssertEqual("".data(using: .utf8)!.sqlLiteral, "NULL") - XCTAssertEqual("foo".data(using: .utf8)!.sqlLiteral, "x'666f6f'") + XCTAssertEqual("".data(using: .utf8)!.databaseValue.sql, "NULL") + XCTAssertEqual("foo".data(using: .utf8)!.databaseValue.sql, "X'666F6F'") } } diff --git a/Tests/Private/SQLExpressionLiteralTests.swift b/Tests/Private/SQLExpressionLiteralTests.swift index dc9546a45..696bc0241 100644 --- a/Tests/Private/SQLExpressionLiteralTests.swift +++ b/Tests/Private/SQLExpressionLiteralTests.swift @@ -11,20 +11,20 @@ import XCTest class SQLExpressionLiteralTests: GRDBTestCase { func testWithArguments() { - let expression = Column("foo").collating("NOCASE") == "'fooéı👨👨🏿🇫🇷🇨🇮'" && Column("baz") >= 1 + let expression = Column("foo").collating(.nocase) == "'fooéı👨👨🏿🇫🇷🇨🇮'" && Column("baz") >= 1 var arguments: StatementArguments? = StatementArguments() - let sql = expression.sql(&arguments) + let sql = expression.expressionSQL(&arguments) XCTAssertEqual(sql, "((\"foo\" = ? COLLATE NOCASE) AND (\"baz\" >= ?))") let values = arguments!.values XCTAssertEqual(values.count, 2) - XCTAssertEqual((values[0] as! String), "'fooéı👨👨🏿🇫🇷🇨🇮'") - XCTAssertEqual((values[1] as! Int), 1) + XCTAssertEqual(values[0], "'fooéı👨👨🏿🇫🇷🇨🇮'".databaseValue) + XCTAssertEqual(values[1], 1.databaseValue) } func testWithoutArguments() { - let expression = Column("foo").collating("NOCASE") == "'fooéı👨👨🏿🇫🇷🇨🇮'" && Column("baz") >= 1 + let expression = Column("foo").collating(.nocase) == "'fooéı👨👨🏿🇫🇷🇨🇮'" && Column("baz") >= 1 var arguments: StatementArguments? = nil - let sql = expression.sql(&arguments) + let sql = expression.expressionSQL(&arguments) XCTAssertEqual(sql, "((\"foo\" = '''fooéı👨👨🏿🇫🇷🇨🇮''' COLLATE NOCASE) AND (\"baz\" >= 1))") } } diff --git a/Tests/Public/Core/Database/TextEncodingTests.swift b/Tests/Public/Core/Database/TextEncodingTests.swift new file mode 100644 index 000000000..ce1427bb9 --- /dev/null +++ b/Tests/Public/Core/Database/TextEncodingTests.swift @@ -0,0 +1,61 @@ +import XCTest +#if USING_SQLCIPHER + import GRDBCipher +#elseif USING_CUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +extension Database.TextEncoding : DatabaseValueConvertible { } + +class TextEncodingTests : GRDBTestCase { + + func testDefaultEncoding() { + assertNoError { + dbConfiguration = Configuration() + let dbQueue = try makeDatabaseQueue() + dbQueue.inDatabase { db in + let encoding = Database.TextEncoding.fetchOne(db, "PRAGMA encoding") + XCTAssertEqual(encoding, .utf8) + XCTAssertEqual(db.configuration.textEncoding, .utf8) + } + XCTAssertEqual(dbQueue.configuration.textEncoding, .utf8) + } + } + + func testCustomEncoding() { + assertNoError { + dbConfiguration.textEncoding = .utf16le + let dbQueue = try makeDatabaseQueue() + dbQueue.inDatabase { db in + let encoding = Database.TextEncoding.fetchOne(db, "PRAGMA encoding") + XCTAssertEqual(encoding, .utf16le) + XCTAssertEqual(db.configuration.textEncoding, .utf16le) + } + XCTAssertEqual(dbQueue.configuration.textEncoding, .utf16le) + } + } + + func testDatabaseKnowsItsEncoding() { + assertNoError { + let dbQueue = try makeDatabaseQueue(filename: "db.sqlite") + // Something has to be written so that the encoding is actually locked + try dbQueue.inDatabase { db in + try db.create(table: "foo") { t in + t.column("id", .integer) + } + } + } + assertNoError { + dbConfiguration.textEncoding = .utf16le + let dbQueue = try makeDatabaseQueue(filename: "db.sqlite") + dbQueue.inDatabase { db in + let encoding = Database.TextEncoding.fetchOne(db, "PRAGMA encoding") + XCTAssertEqual(encoding, .utf8) + XCTAssertEqual(db.configuration.textEncoding, .utf8) + } + XCTAssertEqual(dbQueue.configuration.textEncoding, .utf8) + } + } +} diff --git a/Tests/Public/QueryInterfaceRequest/SQLSupportTests.swift b/Tests/Public/QueryInterfaceRequest/SQLSupportTests.swift index 4fa929f68..b4f9be7ec 100644 --- a/Tests/Public/QueryInterfaceRequest/SQLSupportTests.swift +++ b/Tests/Public/QueryInterfaceRequest/SQLSupportTests.swift @@ -393,10 +393,10 @@ class SQLSupportTests: GRDBTestCase { "SELECT * FROM \"readers\" WHERE \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.age == false)), - "SELECT * FROM \"readers\" WHERE (NOT \"age\")") + "SELECT * FROM \"readers\" WHERE NOT \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.filter(false == Col.age)), - "SELECT * FROM \"readers\" WHERE (NOT \"age\")") + "SELECT * FROM \"readers\" WHERE NOT \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.filter(true == true)), "SELECT * FROM \"readers\" WHERE 1") @@ -472,10 +472,10 @@ class SQLSupportTests: GRDBTestCase { XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.age != true)), - "SELECT * FROM \"readers\" WHERE (NOT \"age\")") + "SELECT * FROM \"readers\" WHERE NOT \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.filter(true != Col.age)), - "SELECT * FROM \"readers\" WHERE (NOT \"age\")") + "SELECT * FROM \"readers\" WHERE NOT \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.age != false)), "SELECT * FROM \"readers\" WHERE \"age\"") @@ -667,7 +667,7 @@ class SQLSupportTests: GRDBTestCase { XCTAssertEqual( sql(dbQueue, tableRequest.filter(!Col.age)), - "SELECT * FROM \"readers\" WHERE (NOT \"age\")") + "SELECT * FROM \"readers\" WHERE NOT \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.age && true)), "SELECT * FROM \"readers\" WHERE (\"age\" AND 1)") @@ -689,6 +689,9 @@ class SQLSupportTests: GRDBTestCase { XCTAssertEqual( sql(dbQueue, tableRequest.filter((Col.age != nil || Col.name != nil) && Col.id != nil)), "SELECT * FROM \"readers\" WHERE (((\"age\" IS NOT NULL) OR (\"name\" IS NOT NULL)) AND (\"id\" IS NOT NULL))") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Col.age > 18) && !(Col.name > "foo"))), + "SELECT * FROM \"readers\" WHERE (NOT (\"age\" > 18) AND NOT (\"name\" > 'foo'))") } @@ -834,7 +837,7 @@ class SQLSupportTests: GRDBTestCase { optInt = 1 XCTAssertEqual( sql(dbQueue, tableRequest.filter(optInt ?? Col.age)), - "SELECT * FROM \"readers\" WHERE IFNULL(1, \"age\")") + "SELECT * FROM \"readers\" WHERE 1") XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.age ?? Col.age)), "SELECT * FROM \"readers\" WHERE IFNULL(\"age\", \"age\")") @@ -913,6 +916,17 @@ class SQLSupportTests: GRDBTestCase { } + // MARK: - LIKE operator + + func testLikeOperator() { + let dbQueue = try! makeDatabaseQueue() + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Col.name.like("%foo"))), + "SELECT * FROM \"readers\" WHERE (\"name\" LIKE '%foo')") + } + + // MARK: - Function func testCustomFunction() { diff --git a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift index e92fa69ef..856cdf439 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -180,7 +180,7 @@ class SQLTableBuilderTests: GRDBTestCase { "\"a\" INTEGER DEFAULT 1, " + "\"b\" INTEGER DEFAULT 1.0, " + "\"c\" INTEGER DEFAULT '''fooéı👨👨🏿🇫🇷🇨🇮''', " + - "\"d\" INTEGER DEFAULT x'666f6f', " + + "\"d\" INTEGER DEFAULT X'666F6F', " + "\"e\" INTEGER DEFAULT NULL" + ")") as String)