From d7ef314a156963a8b480e8004a68d13ba9ee9e62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 22 Jan 2020 18:59:30 +0100 Subject: [PATCH 01/24] SQLLiteral is now a promise that needs an SQLGenerationContext --- GRDB.xcodeproj/project.pbxproj | 4 +- GRDB/Core/Database+Statements.swift | 4 +- GRDB/Core/SQLLiteral.swift | 77 +++++++++++++------ GRDB/Core/SQLRequest.swift | 9 ++- .../SQL/SQLExpression+QueryInterface.swift | 9 +-- GRDB/QueryInterface/SQL/SQLSelectable.swift | 7 +- 6 files changed, 66 insertions(+), 44 deletions(-) diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index eb5aeab90..1bf39b537 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -2559,11 +2559,11 @@ }; 56E5D7C91B4D3FED00430942 = { CreatedOnToolsVersion = 7.0; - LastSwiftMigration = 1020; + LastSwiftMigration = 1130; }; 56E5D7D21B4D3FEE00430942 = { CreatedOnToolsVersion = 7.0; - LastSwiftMigration = 0800; + LastSwiftMigration = 1130; ProvisioningStyle = Manual; }; 56E5D7F81B4D422D00430942 = { diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 11046d99e..fa7b2e15e 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -165,12 +165,12 @@ extension Database { // // And before we return, we'll check that all arguments were consumed. - var arguments = sqlLiteral.arguments + var (sql, arguments) = sqlLiteral.resolveWithDefaultContext() let initialValuesCount = arguments.values.count // Build a C string (SQLite wants that), and execute SQL statements one // after the other. - try sqlLiteral.sql.utf8CString.withUnsafeBufferPointer { buffer in + try sql.utf8CString.withUnsafeBufferPointer { buffer in guard let sqlStart = buffer.baseAddress else { return } let sqlEnd = sqlStart + buffer.count // past \0 var statementStart = sqlStart diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index 7aeb9c74c..95ef40ffb 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -10,8 +10,25 @@ /// try db.execute(literal: query) /// } public struct SQLLiteral { - public private(set) var sql: String - public private(set) var arguments: StatementArguments + public var sql: String { + return resolveWithDefaultContext().sql + } + + public var arguments: StatementArguments { + return resolveWithDefaultContext().arguments + } + + let resolve: (inout SQLGenerationContext) -> String + + func resolveWithDefaultContext() -> (sql: String, arguments: StatementArguments) { + var context = SQLGenerationContext.literalGenerationContext(withArguments: true) + let sql = resolve(&context) + return (sql: sql, arguments: context.arguments!) + } + + init(_ resolve: @escaping (inout SQLGenerationContext) -> String) { + self.resolve = resolve + } /// Creates an SQLLiteral from a plain SQL string, and eventual arguments. /// @@ -21,13 +38,27 @@ public struct SQLLiteral { /// sql: "UPDATE player SET name = ? WHERE id = ?", /// arguments: [name, id]) public init(sql: String, arguments: StatementArguments = StatementArguments()) { - self.sql = sql - self.arguments = arguments + self.init({ context in + if context.append(arguments: arguments) == false { + // GRDB limitation: we don't know how to look for `?` in sql and + // replace them with literals. + fatalError("Not implemented") + } + return sql + }) } /// Returns a literal whose SQL is transformed by the given closure. - public func mapSQL(_ transform: (String) throws -> String) rethrows -> SQLLiteral { - return try map(\.sql, transform) + public func mapSQL(_ transform: @escaping (String) -> String) -> SQLLiteral { + flatMap { sql in + SQLLiteral { _ in transform(sql) } + } + } + + func flatMap(_ transform: @escaping (_ sql: String) -> SQLLiteral) -> SQLLiteral { + return SQLLiteral { context in + transform(self.resolve(&context)).resolve(&context) + } } } @@ -52,8 +83,11 @@ extension SQLLiteral { /// var query: SQLLiteral = "SELECT * FROM player " /// query += "WHERE name = \(name)" public static func += (lhs: inout SQLLiteral, rhs: SQLLiteral) { - lhs.sql += rhs.sql - lhs.arguments += rhs.arguments + lhs = lhs.flatMap { lSQL in + SQLLiteral { context in + lSQL + rhs.resolve(&context) + } + } } /// Appends an SQLLiteral to the receiver. @@ -86,19 +120,14 @@ extension Sequence where Element == SQLLiteral { /// ] /// let query = components.joined(separator: " ") public func joined(separator: String = "") -> SQLLiteral { - var sql = "" - var arguments = StatementArguments() - var first = true - for literal in self { - if first { - first = false - } else { - sql += separator - } - sql += literal.sql - arguments += literal.arguments - } - return SQLLiteral(sql: sql, arguments: arguments) + // Calling the two properties `sql` and `arguments` must not consume the + // sequence twice, or we would get inconsistent values if the sequence + // does not yield the same elements on the two distinct iterations. + // So let's turn the sequence into a collection first. + // + // TODO: consider deprecating the two `sql` and `arguments` properties, + // and provide a more efficient implementation of this method. + return Array(self).joined(separator: separator) } } @@ -113,9 +142,9 @@ extension Collection where Element == SQLLiteral { /// ] /// let query = components.joined(separator: " ") public func joined(separator: String = "") -> SQLLiteral { - let sql = map { $0.sql }.joined(separator: separator) - let arguments = reduce(into: StatementArguments()) { $0 += $1.arguments } - return SQLLiteral(sql: sql, arguments: arguments) + return SQLLiteral { context in + self.map { $0.resolve(&context) }.joined(separator: separator) + } } } diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index 5dd439fb0..7dd398889 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -146,16 +146,17 @@ public struct SQLRequest: FetchRequest { /// /// :nodoc: public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + let (sql, arguments) = sqlLiteral.resolveWithDefaultContext() let statement: SelectStatement switch cache { case .none: - statement = try db.makeSelectStatement(sql: sqlLiteral.sql) + statement = try db.makeSelectStatement(sql: sql) case .public?: - statement = try db.cachedSelectStatement(sql: sqlLiteral.sql) + statement = try db.cachedSelectStatement(sql: sql) case .internal?: - statement = try db.internalCachedSelectStatement(sql: sqlLiteral.sql) + statement = try db.internalCachedSelectStatement(sql: sql) } - try statement.setArgumentsWithValidation(sqlLiteral.arguments) + try statement.setArgumentsWithValidation(arguments) return PreparedRequest(statement: statement, adapter: adapter) } } diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index f772d78cb..5e65d079f 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -35,7 +35,9 @@ extension SQLExpression { /// SQLExpressionLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]) public struct SQLExpressionLiteral: SQLExpression { private let sqlLiteral: SQLLiteral + public var sql: String { return sqlLiteral.sql } + public var arguments: StatementArguments { return sqlLiteral.arguments } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -71,12 +73,7 @@ public struct SQLExpressionLiteral: SQLExpression { if wrappedInParenthesis { return "(\(expressionSQL(&context, wrappedInParenthesis: false)))" } - if context.append(arguments: sqlLiteral.arguments) == false { - // GRDB limitation: we don't know how to look for `?` in sql and - // replace them with literals. - fatalError("Not implemented") - } - return sqlLiteral.sql + return sqlLiteral.resolve(&context) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) diff --git a/GRDB/QueryInterface/SQL/SQLSelectable.swift b/GRDB/QueryInterface/SQL/SQLSelectable.swift index a0497b7d1..4319989f1 100644 --- a/GRDB/QueryInterface/SQL/SQLSelectable.swift +++ b/GRDB/QueryInterface/SQL/SQLSelectable.swift @@ -33,12 +33,7 @@ struct SQLSelectionLiteral: SQLSelectable { } func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { - if context.append(arguments: sqlLiteral.arguments) == false { - // GRDB limitation: we don't know how to look for `?` in sql and - // replace them with with literals. - fatalError("Not implemented") - } - return sqlLiteral.sql + return sqlLiteral.resolve(&context) } func countedSQL(_ context: inout SQLGenerationContext) -> String { From 5e67ca5566530efeebe9b07dd2e134d5cbf75d8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 22 Jan 2020 19:22:17 +0100 Subject: [PATCH 02/24] Deprecate SQLExpressionLiteral, hide SQLSelectionLiteral, introduce SQLLiteral.sqlExpression and .sqlSelectable --- GRDB/Core/SQLLiteral.swift | 124 ++++++++++++++++++ .../Request/QueryInterfaceRequest.swift | 2 +- .../Request/RequestProtocols.swift | 10 +- .../SQL/SQLExpression+QueryInterface.swift | 62 --------- GRDB/QueryInterface/SQL/SQLSelectable.swift | 39 ------ .../Schema/TableDefinition.swift | 6 +- 6 files changed, 133 insertions(+), 110 deletions(-) diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index 95ef40ffb..16e006f7a 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -109,6 +109,21 @@ extension SQLLiteral { } } +extension SQLLiteral { + /// Creates an SQL literal expression. + /// + /// SQLLiteral(sql: "1 + 2").sqlExpression + /// SQLLiteral(sql: "? + ?", arguments: [1, 2]).sqlExpression + /// SQLLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]).sqlExpression + public var sqlExpression: SQLExpression { + return SQLExpressionLiteral(sqlLiteral: self) + } + + var sqlSelectable: SQLSelectable { + return SQLSelectionLiteral(sqlLiteral: self) + } +} + extension Sequence where Element == SQLLiteral { /// Returns the concatenated SQLLiteral of this sequence of literals, /// inserting the given separator between each element. @@ -173,3 +188,112 @@ extension SQLLiteral: ExpressibleByStringInterpolation { } } #endif + +// MARK: - SQLExpressionLiteral + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// SQLExpressionLiteral is an expression built from a raw SQL snippet. +/// +/// SQLExpressionLiteral(sql: "1 + 2") +/// +/// The SQL literal may contain `?` and colon-prefixed arguments: +/// +/// SQLExpressionLiteral(sql: "? + ?", arguments: [1, 2]) +/// SQLExpressionLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]) +public struct SQLExpressionLiteral: SQLExpression { + private let sqlLiteral: SQLLiteral + + public var sql: String { return sqlLiteral.sql } + + public var arguments: StatementArguments { return sqlLiteral.arguments } + + // Prefer SQLLiteral.sqlExpression + fileprivate init(sqlLiteral: SQLLiteral) { + self.sqlLiteral = sqlLiteral + } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// Creates an SQL literal expression. + /// + /// SQLExpressionLiteral(sql: "1 + 2") + /// SQLExpressionLiteral(sql: "? + ?", arguments: [1, 2]) + /// SQLExpressionLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]) + @available(*, deprecated, message: "Use SQLiteral.sqlExpression instead") + public init(sql: String, arguments: StatementArguments = StatementArguments()) { + self.init(sqlLiteral: SQLLiteral(sql: sql, arguments: arguments)) + } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// Creates an SQL literal expression. + /// + /// SQLExpressionLiteral(literal: SQLLiteral(sql: "1 + 2") + /// SQLExpressionLiteral(literal: SQLLiteral(sql: "? + ?", arguments: [1, 2])) + /// SQLExpressionLiteral(literal: SQLLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2])) + /// + /// With Swift 5, you can safely embed raw values in your SQL queries, + /// without any risk of syntax errors or SQL injection: + /// + /// SQLExpressionLiteral(literal: "\(1) + \(2)") + @available(*, deprecated, message: "Use SQLiteral.sqlExpression instead") + public init(literal sqlLiteral: SQLLiteral) { + self.init(sqlLiteral: sqlLiteral) + } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String { + if wrappedInParenthesis { + return "(\(expressionSQL(&context, wrappedInParenthesis: false)))" + } + return sqlLiteral.resolve(&context) + } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return self + } +} + +// MARK: - SQLSelectionLiteral + +private struct SQLSelectionLiteral: SQLSelectable { + private let sqlLiteral: SQLLiteral + + // Prefer SQLLiteral.sqlSelectable + fileprivate init(sqlLiteral: SQLLiteral) { + self.sqlLiteral = sqlLiteral + } + + func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { + return sqlLiteral.resolve(&context) + } + + func countedSQL(_ context: inout SQLGenerationContext) -> String { + fatalError(""" + Selection literals can't be counted. \ + To resolve this error, select one or several SQLExpressionLiteral instead. + """) + } + + func count(distinct: Bool) -> SQLCount? { + fatalError(""" + Selection literals can't be counted. \ + To resolve this error, select one or several SQLExpressionLiteral instead. + """) + } + + func columnCount(_ db: Database) throws -> Int { + fatalError(""" + Selection literals don't known how many columns they contain. \ + To resolve this error, select one or several SQLExpressionLiteral instead. + """) + } + + func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { + return self + } +} diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 839724348..f0cc36f57 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -212,7 +212,7 @@ extension QueryInterfaceRequest: SelectionRequest { as type: RowDecoder.Type = RowDecoder.self) -> QueryInterfaceRequest { - return select(SQLSelectionLiteral(literal: sqlLiteral), as: type) + return select(sqlLiteral.sqlSelectable, as: type) } /// Creates a request which appends *selection*. diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 9c6a8cbf1..672d221b4 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -91,7 +91,7 @@ extension SelectionRequest { /// .select(literal: SQLLiteral(sql: "email")) public func select(literal sqlLiteral: SQLLiteral) -> Self { // NOT TESTED - return select(SQLSelectionLiteral(literal: sqlLiteral)) + return select(sqlLiteral.sqlSelectable) } /// Creates a request which appends *selection*. @@ -174,7 +174,7 @@ extension FilteredRequest { /// request = request.filter(literal: "name = \("O'Brien")") public func filter(literal sqlLiteral: SQLLiteral) -> Self { // NOT TESTED - return filter(SQLExpressionLiteral(literal: sqlLiteral)) + return filter(sqlLiteral.sqlExpression) } /// Creates a request that matches nothing. @@ -369,7 +369,7 @@ extension AggregatingRequest { /// Creates a request with a new grouping. public func group(literal sqlLiteral: SQLLiteral) -> Self { // NOT TESTED - return group(SQLExpressionLiteral(literal: sqlLiteral)) + return group(sqlLiteral.sqlExpression) } /// Creates a request with the provided *sql* added to the @@ -382,7 +382,7 @@ extension AggregatingRequest { /// eventual set of already applied predicates. public func having(literal sqlLiteral: SQLLiteral) -> Self { // NOT TESTED - return having(SQLExpressionLiteral(literal: sqlLiteral)) + return having(sqlLiteral.sqlExpression) } } @@ -496,7 +496,7 @@ extension OrderedRequest { /// .order(sql: "name") public func order(literal sqlLiteral: SQLLiteral) -> Self { // NOT TESTED - return order(SQLExpressionLiteral(literal: sqlLiteral)) + return order(sqlLiteral.sqlExpression) } } diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index 5e65d079f..38bc53c5a 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -21,68 +21,6 @@ extension SQLExpression { } } -// MARK: - SQLExpressionLiteral - -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// -/// SQLExpressionLiteral is an expression built from a raw SQL snippet. -/// -/// SQLExpressionLiteral(sql: "1 + 2") -/// -/// The SQL literal may contain `?` and colon-prefixed arguments: -/// -/// SQLExpressionLiteral(sql: "? + ?", arguments: [1, 2]) -/// SQLExpressionLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]) -public struct SQLExpressionLiteral: SQLExpression { - private let sqlLiteral: SQLLiteral - - public var sql: String { return sqlLiteral.sql } - - public var arguments: StatementArguments { return sqlLiteral.arguments } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// Creates an SQL literal expression. - /// - /// SQLExpressionLiteral(sql: "1 + 2") - /// SQLExpressionLiteral(sql: "? + ?", arguments: [1, 2]) - /// SQLExpressionLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]) - public init(sql: String, arguments: StatementArguments = StatementArguments()) { - self.init(literal: SQLLiteral(sql: sql, arguments: arguments)) - } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// Creates an SQL literal expression. - /// - /// SQLExpressionLiteral(literal: SQLLiteral(sql: "1 + 2") - /// SQLExpressionLiteral(literal: SQLLiteral(sql: "? + ?", arguments: [1, 2])) - /// SQLExpressionLiteral(literal: SQLLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2])) - /// - /// With Swift 5, you can safely embed raw values in your SQL queries, - /// without any risk of syntax errors or SQL injection: - /// - /// SQLExpressionLiteral(literal: "\(1) + \(2)") - public init(literal sqlLiteral: SQLLiteral) { - self.sqlLiteral = sqlLiteral - } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// :nodoc: - public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String { - if wrappedInParenthesis { - return "(\(expressionSQL(&context, wrappedInParenthesis: false)))" - } - return sqlLiteral.resolve(&context) - } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// :nodoc: - public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return self - } -} - // MARK: - SQLExpressionUnary /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) diff --git a/GRDB/QueryInterface/SQL/SQLSelectable.swift b/GRDB/QueryInterface/SQL/SQLSelectable.swift index 4319989f1..c90ed50c8 100644 --- a/GRDB/QueryInterface/SQL/SQLSelectable.swift +++ b/GRDB/QueryInterface/SQL/SQLSelectable.swift @@ -23,45 +23,6 @@ public protocol SQLSelectable { func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable } -// MARK: - SQLSelectionLiteral - -struct SQLSelectionLiteral: SQLSelectable { - private let sqlLiteral: SQLLiteral - - init(literal sqlLiteral: SQLLiteral) { - self.sqlLiteral = sqlLiteral - } - - func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { - return sqlLiteral.resolve(&context) - } - - func countedSQL(_ context: inout SQLGenerationContext) -> String { - fatalError(""" - Selection literals can't be counted. \ - To resolve this error, select one or several SQLExpressionLiteral instead. - """) - } - - func count(distinct: Bool) -> SQLCount? { - fatalError(""" - Selection literals can't be counted. \ - To resolve this error, select one or several SQLExpressionLiteral instead. - """) - } - - func columnCount(_ db: Database) throws -> Int { - fatalError(""" - Selection literals don't known how many columns they contain. \ - To resolve this error, select one or several SQLExpressionLiteral instead. - """) - } - - func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { - return self - } -} - // MARK: - Counting /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index 10a18d68b..726252f90 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -521,7 +521,7 @@ public final class TableDefinition { /// /// - parameter sql: An SQL snippet public func check(sql: String) { - checkConstraints.append(SQLExpressionLiteral(sql: sql)) + checkConstraints.append(SQLLiteral(sql: sql).sqlExpression) } fileprivate func sql(_ db: Database) throws -> String { @@ -850,7 +850,7 @@ public final class ColumnDefinition { /// - returns: Self so that you can further refine the column definition. @discardableResult public func check(sql: String) -> Self { - checkConstraints.append(SQLExpressionLiteral(sql: sql)) + checkConstraints.append(SQLLiteral(sql: sql).sqlExpression) return self } @@ -882,7 +882,7 @@ public final class ColumnDefinition { /// - returns: Self so that you can further refine the column definition. @discardableResult public func defaults(sql: String) -> Self { - defaultExpression = SQLExpressionLiteral(sql: sql) + defaultExpression = SQLLiteral(sql: sql).sqlExpression return self } From 65c94590ebdb24455d09fb1bb7a36cea6ba0a646 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 22 Jan 2020 20:32:11 +0100 Subject: [PATCH 03/24] Make SQLLiteral able to be qualified with a table alias --- GRDB/Core/Database+Statements.swift | 2 +- GRDB/Core/SQLLiteral.swift | 118 +++++++++++++++++++--------- GRDB/Core/SQLRequest.swift | 2 +- 3 files changed, 82 insertions(+), 40 deletions(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index fa7b2e15e..40b8ab1c6 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -165,7 +165,7 @@ extension Database { // // And before we return, we'll check that all arguments were consumed. - var (sql, arguments) = sqlLiteral.resolveWithDefaultContext() + var (sql, arguments) = sqlLiteral.sqlWithDefaultContext() let initialValuesCount = arguments.values.count // Build a C string (SQLite wants that), and execute SQL statements one diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index 16e006f7a..cd11cec01 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -10,24 +10,66 @@ /// try db.execute(literal: query) /// } public struct SQLLiteral { + enum Element { + case sql(String, StatementArguments) + case sqlLiteral(SQLLiteral) + case expression(SQLExpression) + case selectable(SQLSelectable) + case orderingTerm(SQLOrderingTerm) + case map(SQLLiteral, (String) -> String) + + func sql(_ context: inout SQLGenerationContext) -> String { + switch self { + case let .sql(sql, arguments): + if context.append(arguments: arguments) == false { + // GRDB limitation: we don't know how to look for `?` in sql and + // replace them with literals. + fatalError("Not implemented") + } + return sql + case let .sqlLiteral(sqlLiteral): + return sqlLiteral.sql(&context) + case let .expression(expression): + return expression.expressionSQL(&context, wrappedInParenthesis: false) + case let .selectable(selectable): + return selectable.resultColumnSQL(&context) + case let .orderingTerm(orderingTerm): + return orderingTerm.orderingTermSQL(&context) + case let .map(sqlLiteral, transform): + return transform(sqlLiteral.sql(&context)) + } + } + + func qualified(with alias: TableAlias) -> Element { + switch self { + case .sql: + return self + case let .sqlLiteral(sqlLiteral): + return .sqlLiteral(sqlLiteral.qualified(with: alias)) + case let .expression(expression): + return .expression(expression.qualifiedExpression(with: alias)) + case let .selectable(selectable): + return .selectable(selectable.qualifiedSelectable(with: alias)) + case let .orderingTerm(orderingTerm): + return .orderingTerm(orderingTerm.qualifiedOrdering(with: alias)) + case let .map(sqlLiteral, transform): + return .map(sqlLiteral.qualified(with: alias), transform) + } + } + } + public var sql: String { - return resolveWithDefaultContext().sql + return sqlWithDefaultContext().sql } public var arguments: StatementArguments { - return resolveWithDefaultContext().arguments + return sqlWithDefaultContext().arguments } - let resolve: (inout SQLGenerationContext) -> String + var elements: [Element] - func resolveWithDefaultContext() -> (sql: String, arguments: StatementArguments) { - var context = SQLGenerationContext.literalGenerationContext(withArguments: true) - let sql = resolve(&context) - return (sql: sql, arguments: context.arguments!) - } - - init(_ resolve: @escaping (inout SQLGenerationContext) -> String) { - self.resolve = resolve + init(elements: [Element]) { + self.elements = elements } /// Creates an SQLLiteral from a plain SQL string, and eventual arguments. @@ -38,32 +80,33 @@ public struct SQLLiteral { /// sql: "UPDATE player SET name = ? WHERE id = ?", /// arguments: [name, id]) public init(sql: String, arguments: StatementArguments = StatementArguments()) { - self.init({ context in - if context.append(arguments: arguments) == false { - // GRDB limitation: we don't know how to look for `?` in sql and - // replace them with literals. - fatalError("Not implemented") - } - return sql - }) + self.init(elements: [.sql(sql, arguments)]) } /// Returns a literal whose SQL is transformed by the given closure. public func mapSQL(_ transform: @escaping (String) -> String) -> SQLLiteral { - flatMap { sql in - SQLLiteral { _ in transform(sql) } - } + return SQLLiteral(elements: [.map(self, transform)]) } - func flatMap(_ transform: @escaping (_ sql: String) -> SQLLiteral) -> SQLLiteral { - return SQLLiteral { context in - transform(self.resolve(&context)).resolve(&context) + func sql(_ context: inout SQLGenerationContext) -> String { + var sql = "" + for element in elements { + sql += element.sql(&context) } + return sql + } + + func sqlWithDefaultContext() -> (sql: String, arguments: StatementArguments) { + var context = SQLGenerationContext.literalGenerationContext(withArguments: true) + let sql = self.sql(&context) + return (sql: sql, arguments: context.arguments!) + } + + fileprivate func qualified(with alias: TableAlias) -> SQLLiteral { + return SQLLiteral(elements: elements.map { $0.qualified(with: alias) }) } } -extension SQLLiteral: KeyPathRefining { } - extension SQLLiteral { /// Returns the SQLLiteral produced by the concatenation of two literals. /// @@ -83,11 +126,7 @@ extension SQLLiteral { /// var query: SQLLiteral = "SELECT * FROM player " /// query += "WHERE name = \(name)" public static func += (lhs: inout SQLLiteral, rhs: SQLLiteral) { - lhs = lhs.flatMap { lSQL in - SQLLiteral { context in - lSQL + rhs.resolve(&context) - } - } + lhs.elements += rhs.elements } /// Appends an SQLLiteral to the receiver. @@ -157,8 +196,11 @@ extension Collection where Element == SQLLiteral { /// ] /// let query = components.joined(separator: " ") public func joined(separator: String = "") -> SQLLiteral { - return SQLLiteral { context in - self.map { $0.resolve(&context) }.joined(separator: separator) + if separator.isEmpty { + return SQLLiteral(elements: Array(map { $0.elements }.joined())) + } else { + let separator = SQLLiteral.Element.sql(separator, StatementArguments()) + return SQLLiteral(elements: Array(map { $0.elements }.joined(separator: CollectionOfOne(separator)))) } } } @@ -248,13 +290,13 @@ public struct SQLExpressionLiteral: SQLExpression { if wrappedInParenthesis { return "(\(expressionSQL(&context, wrappedInParenthesis: false)))" } - return sqlLiteral.resolve(&context) + return sqlLiteral.sql(&context) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return self + return sqlLiteral.qualified(with: alias).sqlExpression } } @@ -269,7 +311,7 @@ private struct SQLSelectionLiteral: SQLSelectable { } func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { - return sqlLiteral.resolve(&context) + return sqlLiteral.sql(&context) } func countedSQL(_ context: inout SQLGenerationContext) -> String { @@ -294,6 +336,6 @@ private struct SQLSelectionLiteral: SQLSelectable { } func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { - return self + return sqlLiteral.qualified(with: alias).sqlSelectable } } diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index 7dd398889..1c094f2fe 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -146,7 +146,7 @@ public struct SQLRequest: FetchRequest { /// /// :nodoc: public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { - let (sql, arguments) = sqlLiteral.resolveWithDefaultContext() + let (sql, arguments) = sqlLiteral.sqlWithDefaultContext() let statement: SelectStatement switch cache { case .none: From 4811bc3c5b7ca0ea0db422b6e78ba9730abcd57b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 23 Jan 2020 09:08:49 +0100 Subject: [PATCH 04/24] Test SQLLiteral qualification --- GRDB.xcodeproj/project.pbxproj | 12 +- GRDB/Core/SQLInterpolation.swift | 19 +- GRDB/Core/SQLLiteral.swift | 20 +- GRDB/Core/SQLRequest.swift | 2 +- .../SQLInterpolation+QueryInterface.swift | 43 ++-- GRDBCustom.xcodeproj/project.pbxproj | 6 - .../GRDBTests.xcodeproj/project.pbxproj | 6 - .../GRDBTests.xcodeproj/project.pbxproj | 6 - Tests/GRDBTests/SQLInterpolationTests.swift | 210 ------------------ Tests/GRDBTests/SQLLiteralTests.swift | 44 +++- 10 files changed, 80 insertions(+), 288 deletions(-) delete mode 100644 Tests/GRDBTests/SQLInterpolationTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 1bf39b537..d8d1a9881 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -460,8 +460,6 @@ 567ECE4F2222E431009245CA /* GRDB-4.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-4.0.swift */; }; 567ECE502222E431009245CA /* GRDB-4.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-4.0.swift */; }; 567ECE512222E431009245CA /* GRDB-4.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-4.0.swift */; }; - 567F0B2D220F0E2E00D111FB /* SQLInterpolationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F0B2C220F0E2E00D111FB /* SQLInterpolationTests.swift */; }; - 567F0B2E220F0E2E00D111FB /* SQLInterpolationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F0B2C220F0E2E00D111FB /* SQLInterpolationTests.swift */; }; 567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; @@ -984,7 +982,6 @@ AAA4DD2B230F262000C74B15 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */; }; AAA4DD2C230F262000C74B15 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; AAA4DD2D230F262000C74B15 /* QueryInterfaceExtensibilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */; }; - AAA4DD2E230F262000C74B15 /* SQLInterpolationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F0B2C220F0E2E00D111FB /* SQLInterpolationTests.swift */; }; AAA4DD2F230F262000C74B15 /* DatabaseSavepointTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */; }; AAA4DD30230F262000C74B15 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; AAA4DD31230F262000C74B15 /* ValueObservationRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B0704218627F700B38F35 /* ValueObservationRowTests.swift */; }; @@ -1371,7 +1368,6 @@ 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; }; 567ECE4E2222E431009245CA /* GRDB-4.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "GRDB-4.0.swift"; sourceTree = ""; }; - 567F0B2C220F0E2E00D111FB /* SQLInterpolationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLInterpolationTests.swift; sourceTree = ""; }; 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = ""; }; 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = ""; }; 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = ""; }; @@ -2081,7 +2077,6 @@ 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */, 56A2381D1B9C74A90082EB20 /* Row */, 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */, - 567F0B2C220F0E2E00D111FB /* SQLInterpolationTests.swift */, 56B86E72220FF4E000524C16 /* SQLLiteralTests.swift */, 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */, 56A238201B9C74A90082EB20 /* Statement */, @@ -3058,7 +3053,6 @@ 56EA63C6209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */, 5674A71A1F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 5698AC071D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, - 567F0B2E220F0E2E00D111FB /* SQLInterpolationTests.swift in Sources */, 56C3F7561CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, 56B021CD1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 563B0706218627F800B38F35 /* ValueObservationRowTests.swift in Sources */, @@ -3265,7 +3259,6 @@ 562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, 56EA63C5209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */, 56D496BF1D8135D4008276D7 /* TableDefinitionTests.swift in Sources */, - 567F0B2D220F0E2E00D111FB /* SQLInterpolationTests.swift in Sources */, 5674A7171F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 56D496801D813131008276D7 /* StatementColumnConvertibleFetchTests.swift in Sources */, 563B0705218627F800B38F35 /* ValueObservationRowTests.swift in Sources */, @@ -3606,7 +3599,6 @@ AAA4DD2B230F262000C74B15 /* DerivableRequestTests.swift in Sources */, AAA4DD2C230F262000C74B15 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, AAA4DD2D230F262000C74B15 /* QueryInterfaceExtensibilityTests.swift in Sources */, - AAA4DD2E230F262000C74B15 /* SQLInterpolationTests.swift in Sources */, AAA4DD2F230F262000C74B15 /* DatabaseSavepointTests.swift in Sources */, AAA4DD30230F262000C74B15 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, AAA4DD31230F262000C74B15 /* ValueObservationRowTests.swift in Sources */, @@ -4303,7 +4295,7 @@ MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 4.2; + SWIFT_VERSION = 5.0; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; @@ -4351,7 +4343,7 @@ GCC_WARN_UNUSED_VARIABLE = YES; MTL_ENABLE_DEBUG_INFO = NO; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; - SWIFT_VERSION = 4.2; + SWIFT_VERSION = 5.0; VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; diff --git a/GRDB/Core/SQLInterpolation.swift b/GRDB/Core/SQLInterpolation.swift index 9253c01d8..a43ecb3af 100644 --- a/GRDB/Core/SQLInterpolation.swift +++ b/GRDB/Core/SQLInterpolation.swift @@ -1,33 +1,26 @@ #if swift(>=5.0) /// :nodoc: public struct SQLInterpolation: StringInterpolationProtocol { - var context = SQLGenerationContext.literalGenerationContext(withArguments: true) - var sql: String - var arguments: StatementArguments { - get { return context.arguments! } - set { context.arguments = newValue } - } + var elements: [SQLLiteral.Element] public init(literalCapacity: Int, interpolationCount: Int) { - sql = "" - sql.reserveCapacity(literalCapacity + interpolationCount) + elements = [] + elements.reserveCapacity(interpolationCount + 1) } /// "SELECT * FROM player" public mutating func appendLiteral(_ sql: String) { - self.sql += sql + elements.append(.sql(sql)) } /// "SELECT * FROM \(sql: "player")" public mutating func appendInterpolation(sql: String, arguments: StatementArguments = StatementArguments()) { - self.sql += sql - self.arguments += arguments + elements.append(.sql(sql, arguments)) } /// "SELECT * FROM player WHERE \(literal: condition)" public mutating func appendInterpolation(literal sqlLiteral: SQLLiteral) { - sql += sqlLiteral.sql - arguments += sqlLiteral.arguments + elements.append(.sqlLiteral(sqlLiteral)) } } #endif diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index cd11cec01..061d10082 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -11,13 +11,13 @@ /// } public struct SQLLiteral { enum Element { - case sql(String, StatementArguments) - case sqlLiteral(SQLLiteral) + case sql(String, StatementArguments = StatementArguments()) + case sqlLiteral(SQLLiteral, qualified: Bool = false) case expression(SQLExpression) case selectable(SQLSelectable) case orderingTerm(SQLOrderingTerm) case map(SQLLiteral, (String) -> String) - + func sql(_ context: inout SQLGenerationContext) -> String { switch self { case let .sql(sql, arguments): @@ -27,7 +27,7 @@ public struct SQLLiteral { fatalError("Not implemented") } return sql - case let .sqlLiteral(sqlLiteral): + case let .sqlLiteral(sqlLiteral, _): return sqlLiteral.sql(&context) case let .expression(expression): return expression.expressionSQL(&context, wrappedInParenthesis: false) @@ -44,8 +44,12 @@ public struct SQLLiteral { switch self { case .sql: return self - case let .sqlLiteral(sqlLiteral): - return .sqlLiteral(sqlLiteral.qualified(with: alias)) + case let .sqlLiteral(sqlLiteral, qualified): + if qualified { + return self + } else { + return .sqlLiteral(sqlLiteral.qualified(with: alias), qualified: false /* allow requalification */) + } case let .expression(expression): return .expression(expression.qualifiedExpression(with: alias)) case let .selectable(selectable): @@ -199,7 +203,7 @@ extension Collection where Element == SQLLiteral { if separator.isEmpty { return SQLLiteral(elements: Array(map { $0.elements }.joined())) } else { - let separator = SQLLiteral.Element.sql(separator, StatementArguments()) + let separator = SQLLiteral.Element.sql(separator) return SQLLiteral(elements: Array(map { $0.elements }.joined(separator: CollectionOfOne(separator)))) } } @@ -226,7 +230,7 @@ extension SQLLiteral: ExpressibleByStringInterpolation { /// :nodoc: public init(stringInterpolation sqlInterpolation: SQLInterpolation) { - self.init(sql: sqlInterpolation.sql, arguments: sqlInterpolation.arguments) + self.init(elements: sqlInterpolation.elements) } } #endif diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index 1c094f2fe..42c788238 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -31,7 +31,7 @@ public struct SQLRequest: FetchRequest { /// The request adapter public var adapter: RowAdapter? - private var sqlLiteral: SQLLiteral + var sqlLiteral: SQLLiteral private let cache: Cache? /// Creates a request from an SQL string, optional arguments, and diff --git a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift index 0ec52db3c..44dd55618 100644 --- a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift @@ -6,7 +6,7 @@ extension SQLInterpolation { /// // SELECT * FROM player /// let request: SQLRequest = "SELECT * FROM \(Player.self)" public mutating func appendInterpolation(_ table: T.Type) { - sql += table.databaseTableName.quotedDatabaseIdentifier + appendLiteral(table.databaseTableName.quotedDatabaseIdentifier) } /// Appends the table name of the record. @@ -15,7 +15,7 @@ extension SQLInterpolation { /// let player: Player = ... /// let request: SQLRequest = "INSERT INTO \(tableOf: player) ..." public mutating func appendInterpolation(tableOf record: T) { - sql += type(of: record).databaseTableName.quotedDatabaseIdentifier + appendInterpolation(type(of: record)) } /// Appends the selectable SQL. @@ -25,7 +25,7 @@ extension SQLInterpolation { /// SELECT \(AllColumns()) FROM player /// """ public mutating func appendInterpolation(_ selection: SQLSelectable) { - sql += selection.resultColumnSQL(&context) + elements.append(.selectable(selection)) } /// Appends the expression SQL. @@ -35,7 +35,7 @@ extension SQLInterpolation { /// SELECT \(Column("name")) FROM player /// """ public mutating func appendInterpolation(_ expressible: SQLExpressible & SQLSelectable & SQLOrderingTerm) { - sql += expressible.sqlExpression.expressionSQL(&context, wrappedInParenthesis: false) + elements.append(.expression(expressible.sqlExpression)) } /// Appends the name of the coding key. @@ -47,7 +47,7 @@ extension SQLInterpolation { public mutating func appendInterpolation( _ codingKey: SQLExpressible & SQLSelectable & SQLOrderingTerm & CodingKey) { - sql += codingKey.sqlExpression.expressionSQL(&context, wrappedInParenthesis: false) + elements.append(.expression(codingKey.sqlExpression)) } /// Appends the expression SQL, or NULL if it is nil. @@ -59,9 +59,9 @@ extension SQLInterpolation { /// """ public mutating func appendInterpolation(_ expressible: T?) { if let expressible = expressible { - sql += expressible.sqlExpression.expressionSQL(&context, wrappedInParenthesis: false) + elements.append(.expression(expressible.sqlExpression)) } else { - sql += "NULL" + appendLiteral("NULL") } } @@ -81,7 +81,7 @@ extension SQLInterpolation { public mutating func appendInterpolation(_ expressible: T) where T: Sequence, T.Element: SQLExpressible, T: SQLExpressible { - sql += expressible.sqlExpression.expressionSQL(&context, wrappedInParenthesis: false) + elements.append(.expression(expressible.sqlExpression)) } /// Appends a sequence of expressions, wrapped in parentheses. @@ -119,20 +119,14 @@ extension SQLInterpolation { /// SELECT * FROM player WHERE a IN \(expressions) /// """ public mutating func appendInterpolation(_ sequence: S) where S: Sequence, S.Element == SQLExpression { - sql += "(" - var first = true - for element in sequence { - if first { - first = false - } else { - sql += "," - } - appendInterpolation(element) + let e: [SQLLiteral.Element] = sequence.map { .expression($0.sqlExpression) } + if e.isEmpty { + appendLiteral("(SELECT NULL WHERE NULL)") + } else { + appendLiteral("(") + elements.append(contentsOf: e.map(CollectionOfOne.init(_:)).joined(separator: CollectionOfOne(.sql(",")))) + appendLiteral(")") } - if first { - sql += "SELECT NULL WHERE NULL" - } - sql += ")" } /// Appends the ordering SQL. @@ -142,7 +136,7 @@ extension SQLInterpolation { /// SELECT * FROM player ORDER BY \(Column("name").desc) /// """ public mutating func appendInterpolation(_ ordering: SQLOrderingTerm) { - sql += ordering.orderingTermSQL(&context) + elements.append(.orderingTerm(ordering)) } /// Appends the request SQL, wrapped in parentheses @@ -153,8 +147,9 @@ extension SQLInterpolation { /// SELECT * FROM player WHERE score = \(subQuery) /// """ public mutating func appendInterpolation(_ request: SQLRequest) { - sql += "(" + request.sql + ")" - arguments += request.arguments + appendLiteral("(") + elements.append(.sqlLiteral(request.sqlLiteral, qualified: true /* don't requalify */)) + appendLiteral(")") } } #endif diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 3f0df6147..0c0f43cca 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -323,8 +323,6 @@ 567DAF211EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; }; 567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; }; 567DAF3C1EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; }; - 567F0B30220F196400D111FB /* SQLInterpolationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F0B2F220F196300D111FB /* SQLInterpolationTests.swift */; }; - 567F0B31220F196400D111FB /* SQLInterpolationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F0B2F220F196300D111FB /* SQLInterpolationTests.swift */; }; 567F45AB1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 567F45AF1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 568068341EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; @@ -916,7 +914,6 @@ 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; }; - 567F0B2F220F196300D111FB /* SQLInterpolationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLInterpolationTests.swift; sourceTree = ""; }; 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = ""; }; 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = ""; }; 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; @@ -1587,7 +1584,6 @@ 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */, 56A2381D1B9C74A90082EB20 /* Row */, 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */, - 567F0B2F220F196300D111FB /* SQLInterpolationTests.swift */, 56B86E6E220FF4C800524C16 /* SQLLiteralTests.swift */, 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */, 56A238201B9C74A90082EB20 /* Statement */, @@ -2334,7 +2330,6 @@ 56EA63CA209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */, F3BA80E91CFB3016003DC1BA /* RowAdapterTests.swift in Sources */, 562393371DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, - 567F0B31220F196400D111FB /* SQLInterpolationTests.swift in Sources */, 5674A7161F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 56B021D01D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 563B0703218627DF00B38F35 /* ValueObservationRowTests.swift in Sources */, @@ -2675,7 +2670,6 @@ 56EA63C9209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */, F3BA811D1CFB305F003DC1BA /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, F3BA80AD1CFB2FA6003DC1BA /* DataMemoryTests.swift in Sources */, - 567F0B30220F196400D111FB /* SQLInterpolationTests.swift in Sources */, 5698ACB91DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 5674A7141F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 563B0702218627DF00B38F35 /* ValueObservationRowTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index 23fae7679..02d81be01 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -63,7 +63,6 @@ 564A2003226B89E1001F64F1 /* DatabaseValueConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F4C226B89D1001F64F1 /* DatabaseValueConvertibleFetchTests.swift */; }; 564A2004226B89E1001F64F1 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F4D226B89D2001F64F1 /* AssociationChainSQLTests.swift */; }; 564A2005226B89E1001F64F1 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F4E226B89D2001F64F1 /* SQLExpressionLiteralTests.swift */; }; - 564A2006226B89E1001F64F1 /* SQLInterpolationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F4F226B89D2001F64F1 /* SQLInterpolationTests.swift */; }; 564A2007226B89E1001F64F1 /* FoundationDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F50226B89D2001F64F1 /* FoundationDataTests.swift */; }; 564A2008226B89E1001F64F1 /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F51226B89D2001F64F1 /* RecordInitializersTests.swift */; }; 564A2009226B89E1001F64F1 /* AssociationHasOneThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F52226B89D2001F64F1 /* AssociationHasOneThroughSQLTests.swift */; }; @@ -384,7 +383,6 @@ 564A2147226B8E18001F64F1 /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F3F226B89D0001F64F1 /* DatabaseSnapshotTests.swift */; }; 564A2148226B8E18001F64F1 /* FoundationDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FA0226B89DA001F64F1 /* FoundationDateTests.swift */; }; 564A2149226B8E18001F64F1 /* DatabasePoolFunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F8C226B89D9001F64F1 /* DatabasePoolFunctionTests.swift */; }; - 564A214A226B8E18001F64F1 /* SQLInterpolationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F4F226B89D2001F64F1 /* SQLInterpolationTests.swift */; }; 564A214B226B8E18001F64F1 /* MapCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FB8226B89DD001F64F1 /* MapCursorTests.swift */; }; 564A214C226B8E18001F64F1 /* NumericOverflowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F2E226B89CF001F64F1 /* NumericOverflowTests.swift */; }; 564A214D226B8E18001F64F1 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FAB226B89DC001F64F1 /* RecordMinimalPrimaryKeySingleTests.swift */; }; @@ -464,7 +462,6 @@ 564A1F4C226B89D1001F64F1 /* DatabaseValueConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleFetchTests.swift; sourceTree = ""; }; 564A1F4D226B89D2001F64F1 /* AssociationChainSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainSQLTests.swift; sourceTree = ""; }; 564A1F4E226B89D2001F64F1 /* SQLExpressionLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpressionLiteralTests.swift; sourceTree = ""; }; - 564A1F4F226B89D2001F64F1 /* SQLInterpolationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLInterpolationTests.swift; sourceTree = ""; }; 564A1F50226B89D2001F64F1 /* FoundationDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDataTests.swift; sourceTree = ""; }; 564A1F51226B89D2001F64F1 /* RecordInitializersTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordInitializersTests.swift; sourceTree = ""; }; 564A1F52226B89D2001F64F1 /* AssociationHasOneThroughSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLTests.swift; sourceTree = ""; }; @@ -838,7 +835,6 @@ 564A1F7F226B89D7001F64F1 /* SchedulingWatchdogTests.swift */, 564A1F2A226B89CF001F64F1 /* SelectStatementTests.swift */, 564A1F4E226B89D2001F64F1 /* SQLExpressionLiteralTests.swift */, - 564A1F4F226B89D2001F64F1 /* SQLInterpolationTests.swift */, 564A1FA8226B89DB001F64F1 /* SQLLiteralTests.swift */, 564A1F42226B89D0001F64F1 /* SQLRequestTests.swift */, 564A1F58226B89D3001F64F1 /* StatementArguments+FoundationTests.swift */, @@ -1268,7 +1264,6 @@ 564A1FF6226B89E1001F64F1 /* DatabaseSnapshotTests.swift in Sources */, 564A2057226B89E1001F64F1 /* FoundationDateTests.swift in Sources */, 564A2043226B89E1001F64F1 /* DatabasePoolFunctionTests.swift in Sources */, - 564A2006226B89E1001F64F1 /* SQLInterpolationTests.swift in Sources */, 564A206F226B89E1001F64F1 /* MapCursorTests.swift in Sources */, 564A1FE5226B89E1001F64F1 /* NumericOverflowTests.swift in Sources */, 564A2062226B89E1001F64F1 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, @@ -1473,7 +1468,6 @@ 564A2147226B8E18001F64F1 /* DatabaseSnapshotTests.swift in Sources */, 564A2148226B8E18001F64F1 /* FoundationDateTests.swift in Sources */, 564A2149226B8E18001F64F1 /* DatabasePoolFunctionTests.swift in Sources */, - 564A214A226B8E18001F64F1 /* SQLInterpolationTests.swift in Sources */, 564A214B226B8E18001F64F1 /* MapCursorTests.swift in Sources */, 564A214C226B8E18001F64F1 /* NumericOverflowTests.swift in Sources */, 564A214D226B8E18001F64F1 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index 6b2bbf765..855865e36 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -63,7 +63,6 @@ 564A2003226B89E1001F64F1 /* DatabaseValueConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F4C226B89D1001F64F1 /* DatabaseValueConvertibleFetchTests.swift */; }; 564A2004226B89E1001F64F1 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F4D226B89D2001F64F1 /* AssociationChainSQLTests.swift */; }; 564A2005226B89E1001F64F1 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F4E226B89D2001F64F1 /* SQLExpressionLiteralTests.swift */; }; - 564A2006226B89E1001F64F1 /* SQLInterpolationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F4F226B89D2001F64F1 /* SQLInterpolationTests.swift */; }; 564A2007226B89E1001F64F1 /* FoundationDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F50226B89D2001F64F1 /* FoundationDataTests.swift */; }; 564A2008226B89E1001F64F1 /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F51226B89D2001F64F1 /* RecordInitializersTests.swift */; }; 564A2009226B89E1001F64F1 /* AssociationHasOneThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F52226B89D2001F64F1 /* AssociationHasOneThroughSQLTests.swift */; }; @@ -384,7 +383,6 @@ 564A2147226B8E18001F64F1 /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F3F226B89D0001F64F1 /* DatabaseSnapshotTests.swift */; }; 564A2148226B8E18001F64F1 /* FoundationDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FA0226B89DA001F64F1 /* FoundationDateTests.swift */; }; 564A2149226B8E18001F64F1 /* DatabasePoolFunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F8C226B89D9001F64F1 /* DatabasePoolFunctionTests.swift */; }; - 564A214A226B8E18001F64F1 /* SQLInterpolationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F4F226B89D2001F64F1 /* SQLInterpolationTests.swift */; }; 564A214B226B8E18001F64F1 /* MapCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FB8226B89DD001F64F1 /* MapCursorTests.swift */; }; 564A214C226B8E18001F64F1 /* NumericOverflowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F2E226B89CF001F64F1 /* NumericOverflowTests.swift */; }; 564A214D226B8E18001F64F1 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FAB226B89DC001F64F1 /* RecordMinimalPrimaryKeySingleTests.swift */; }; @@ -466,7 +464,6 @@ 564A1F4C226B89D1001F64F1 /* DatabaseValueConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleFetchTests.swift; sourceTree = ""; }; 564A1F4D226B89D2001F64F1 /* AssociationChainSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainSQLTests.swift; sourceTree = ""; }; 564A1F4E226B89D2001F64F1 /* SQLExpressionLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpressionLiteralTests.swift; sourceTree = ""; }; - 564A1F4F226B89D2001F64F1 /* SQLInterpolationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLInterpolationTests.swift; sourceTree = ""; }; 564A1F50226B89D2001F64F1 /* FoundationDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDataTests.swift; sourceTree = ""; }; 564A1F51226B89D2001F64F1 /* RecordInitializersTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordInitializersTests.swift; sourceTree = ""; }; 564A1F52226B89D2001F64F1 /* AssociationHasOneThroughSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLTests.swift; sourceTree = ""; }; @@ -842,7 +839,6 @@ 564A1F7F226B89D7001F64F1 /* SchedulingWatchdogTests.swift */, 564A1F2A226B89CF001F64F1 /* SelectStatementTests.swift */, 564A1F4E226B89D2001F64F1 /* SQLExpressionLiteralTests.swift */, - 564A1F4F226B89D2001F64F1 /* SQLInterpolationTests.swift */, 564A1FA8226B89DB001F64F1 /* SQLLiteralTests.swift */, 564A1F42226B89D0001F64F1 /* SQLRequestTests.swift */, 564A1F58226B89D3001F64F1 /* StatementArguments+FoundationTests.swift */, @@ -1274,7 +1270,6 @@ 564A1FF6226B89E1001F64F1 /* DatabaseSnapshotTests.swift in Sources */, 564A2057226B89E1001F64F1 /* FoundationDateTests.swift in Sources */, 564A2043226B89E1001F64F1 /* DatabasePoolFunctionTests.swift in Sources */, - 564A2006226B89E1001F64F1 /* SQLInterpolationTests.swift in Sources */, 564A206F226B89E1001F64F1 /* MapCursorTests.swift in Sources */, 564A1FE5226B89E1001F64F1 /* NumericOverflowTests.swift in Sources */, 564A2062226B89E1001F64F1 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, @@ -1479,7 +1474,6 @@ 564A2147226B8E18001F64F1 /* DatabaseSnapshotTests.swift in Sources */, 564A2148226B8E18001F64F1 /* FoundationDateTests.swift in Sources */, 564A2149226B8E18001F64F1 /* DatabasePoolFunctionTests.swift in Sources */, - 564A214A226B8E18001F64F1 /* SQLInterpolationTests.swift in Sources */, 564A214B226B8E18001F64F1 /* MapCursorTests.swift in Sources */, 564A214C226B8E18001F64F1 /* NumericOverflowTests.swift in Sources */, 564A214D226B8E18001F64F1 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, diff --git a/Tests/GRDBTests/SQLInterpolationTests.swift b/Tests/GRDBTests/SQLInterpolationTests.swift deleted file mode 100644 index 8f51b3bbb..000000000 --- a/Tests/GRDBTests/SQLInterpolationTests.swift +++ /dev/null @@ -1,210 +0,0 @@ -#if swift(>=5.0) -import XCTest -#if GRDBCUSTOMSQLITE - @testable import GRDBCustomSQLite -#else - @testable import GRDB -#endif - -class SQLInterpolationTests: GRDBTestCase { - func testSQLInterpolation() { - var sql = SQLInterpolation(literalCapacity: 0, interpolationCount: 2) - - sql.appendInterpolation(sql: "\(1)"); sql.appendLiteral("\n") - sql.appendInterpolation(sql: ":name", arguments: ["name": "Arthur"]) - - XCTAssertEqual(sql.sql, """ - 1 - :name - """) - XCTAssertEqual(sql.arguments, ["name": "Arthur"]) - } - - func testSelectableInterpolation() { - var sql = SQLInterpolation(literalCapacity: 0, interpolationCount: 2) - - // Non-existential - sql.appendInterpolation(AllColumns()); sql.appendLiteral("\n") - // Existential - sql.appendInterpolation(AllColumns() as SQLSelectable) - - XCTAssertEqual(sql.sql, """ - * - * - """) - XCTAssert(sql.arguments.isEmpty) - } - - func testTableInterpolation() { - var sql = SQLInterpolation(literalCapacity: 0, interpolationCount: 1) - - struct Player: TableRecord { } - sql.appendInterpolation(Player.self); sql.appendLiteral("\n") - sql.appendInterpolation(tableOf: Player()) - - XCTAssertEqual(sql.sql, """ - "player" - "player" - """) - XCTAssert(sql.arguments.isEmpty) - } - - func testExpressibleInterpolation() { - var sql = SQLInterpolation(literalCapacity: 0, interpolationCount: 7) - - let a = Column("a") - let b = Column("b") - let integer: Int = 1 - let optionalInteger: Int? = 2 - let nilInteger: Int? = nil - sql.appendInterpolation(a); sql.appendLiteral("\n") - sql.appendInterpolation(a + 1); sql.appendLiteral("\n") - sql.appendInterpolation(2 * (a + 1)); sql.appendLiteral("\n") - sql.appendInterpolation(a < b); sql.appendLiteral("\n") - sql.appendInterpolation(integer); sql.appendLiteral("\n") - sql.appendInterpolation(optionalInteger); sql.appendLiteral("\n") - sql.appendInterpolation(nilInteger); sql.appendLiteral("\n") - sql.appendInterpolation(a == nilInteger) - - XCTAssertEqual(sql.sql, """ - "a" - "a" + ? - ? * ("a" + ?) - "a" < "b" - ? - ? - NULL - "a" IS NULL - """) - XCTAssertEqual(sql.arguments, [1, 2, 1, 1, 2]) - } - - func testDatabaseValueConvertibleInterpolation() { - func test(value: V, isInterpolatedAs dbValue: DatabaseValue) { - var sql = SQLInterpolation(literalCapacity: 0, interpolationCount: 1) - sql.appendInterpolation(value) - XCTAssertEqual(sql.sql, "?") - XCTAssertEqual(sql.arguments, [dbValue]) - } - - struct V: DatabaseValueConvertible { - var databaseValue: DatabaseValue { - return "V".databaseValue - } - - static func fromDatabaseValue(_ dbValue: DatabaseValue) -> V? { - return nil - } - } - - test(value: 42, isInterpolatedAs: 42.databaseValue) - test(value: 1.23, isInterpolatedAs: 1.23.databaseValue) - test(value: "foo", isInterpolatedAs: "foo".databaseValue) - test(value: "foo".data(using: .utf8)!, isInterpolatedAs: "foo".data(using: .utf8)!.databaseValue) - test(value: V(), isInterpolatedAs: "V".databaseValue) - } - - func testDataInterpolation() { - // This test makes sure the Sequence conformance of Data does not - // kick in. - let data = "SQLite".data(using: .utf8)! - var sql = SQLInterpolation(literalCapacity: 0, interpolationCount: 1) - sql.appendInterpolation(data) - XCTAssertEqual(sql.sql, "?") - XCTAssertEqual(sql.arguments, [data]) - } - - func testQualifiedExpressionInterpolation() { - var sql = SQLInterpolation(literalCapacity: 0, interpolationCount: 1) - - sql.appendInterpolation(Column("name").forKey("foo")); sql.appendLiteral("\n") - sql.appendInterpolation(1.databaseValue.forKey("bar")) - - XCTAssertEqual(sql.sql, """ - "name" AS "foo" - ? AS "bar" - """) - XCTAssertEqual(sql.arguments, [1]) - } - - func testCodingKeyInterpolation() { - var sql = SQLInterpolation(literalCapacity: 0, interpolationCount: 1) - - enum CodingKeys: String, CodingKey { - case name - } - sql.appendInterpolation(CodingKeys.name) - - XCTAssertEqual(sql.sql, """ - "name" - """) - XCTAssert(sql.arguments.isEmpty) - } - - func testCodingKeyColumnInterpolation() { - var sql = SQLInterpolation(literalCapacity: 0, interpolationCount: 1) - - enum CodingKeys: String, CodingKey, ColumnExpression { - case name - } - sql.appendInterpolation(CodingKeys.name) - - XCTAssertEqual(sql.sql, """ - "name" - """) - XCTAssert(sql.arguments.isEmpty) - } - - func testExpressibleSequenceInterpolation() throws { - var sql = SQLInterpolation(literalCapacity: 0, interpolationCount: 3) - - let set: Set = [1] - let array = ["foo", "bar", "baz"] - let expressions = [Column("a"), Column("b") + 2] - sql.appendInterpolation(set); sql.appendLiteral("\n") - sql.appendInterpolation(array); sql.appendLiteral("\n") - sql.appendInterpolation(expressions); sql.appendLiteral("\n") - sql.appendInterpolation([]) - - XCTAssertEqual(sql.sql, """ - (?) - (?,?,?) - ("a","b" + ?) - (SELECT NULL WHERE NULL) - """) - XCTAssertEqual(sql.arguments, [1, "foo", "bar", "baz", 2]) - } - - func testOrderingTermInterpolation() { - var sql = SQLInterpolation(literalCapacity: 0, interpolationCount: 1) - - sql.appendInterpolation(Column("name").desc) - - XCTAssertEqual(sql.sql, """ - "name" DESC - """) - XCTAssert(sql.arguments.isEmpty) - } - - func testSQLLiteralInterpolation() { - var sql = SQLInterpolation(literalCapacity: 0, interpolationCount: 3) - - sql.appendInterpolation(1) - sql.appendInterpolation(literal: " + \(2) + ") - sql.appendInterpolation(3) - - XCTAssertEqual(sql.sql, "? + ? + ?") - XCTAssertEqual(sql.arguments, [1, 2, 3]) - } - - func testSQLRequestInterpolation() { - var sql = SQLInterpolation(literalCapacity: 0, interpolationCount: 3) - - sql.appendInterpolation(SQLRequest(sql: "SELECT * FROM player WHERE id = ?", arguments: [42])) - sql.appendInterpolation(SQLRequest(sql: "SELECT * FROM teams WHERE name = ?", arguments: ["Red"])) - - XCTAssertEqual(sql.sql, "(SELECT * FROM player WHERE id = ?)(SELECT * FROM teams WHERE name = ?)") - XCTAssertEqual(sql.arguments, [42, "Red"]) - } -} -#endif diff --git a/Tests/GRDBTests/SQLLiteralTests.swift b/Tests/GRDBTests/SQLLiteralTests.swift index 7c38a676a..0210a9d1e 100644 --- a/Tests/GRDBTests/SQLLiteralTests.swift +++ b/Tests/GRDBTests/SQLLiteralTests.swift @@ -255,16 +255,16 @@ extension SQLLiteralTests { XCTAssertEqual(query.arguments, [data]) } - func testQualifiedExpressionInterpolation() { + func testAliasedExpressionInterpolation() { let query: SQLLiteral = """ - SELECT \(Column("name").forKey("foo")) + SELECT \(Column("name").forKey("foo")), \(1.databaseValue.forKey("bar")) FROM player """ XCTAssertEqual(query.sql, """ - SELECT "name" AS "foo" + SELECT "name" AS "foo", ? AS "bar" FROM player """) - XCTAssert(query.arguments.isEmpty) + XCTAssertEqual(query.arguments, [1]) } func testCodingKeyInterpolation() { @@ -396,5 +396,41 @@ extension SQLLiteralTests { """) XCTAssertEqual(query.arguments, ["name": "Arthur"]) } + + func testQualifiedSQLLiteral() throws { + struct Player: TableRecord { } + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.column("name", .text) + } + let nameColumn = Column("name") + let baseRequest = Player.aliased(TableAlias(name: "p")) + + let alteredNameLiteral = SQLLiteral("\(nameColumn) || \("foo")") + do { + let request = baseRequest.select(literal: alteredNameLiteral) + try assertEqualSQL(db, request, """ + SELECT "p"."name" || 'foo' FROM "player" "p" + """) + } + + let alteredNameColumn = alteredNameLiteral.sqlExpression.forKey("alteredName") + do { + let request = baseRequest.select(alteredNameColumn) + try assertEqualSQL(db, request, """ + SELECT "p"."name" || 'foo' AS "alteredName" FROM "player" "p" + """) + } + + let subQuery: SQLRequest = "SELECT MAX(\(nameColumn)) FROM \(Player.self)" + let conditionLiteral = SQLLiteral("\(nameColumn) = \(subQuery)") + do { + let request = baseRequest.filter(literal: conditionLiteral) + try assertEqualSQL(db, request, """ + SELECT "p".* FROM "player" "p" WHERE "p"."name" = (SELECT MAX("name") FROM "player") + """) + } + } + } } #endif From 6a0cc838da6e5e0d659510a3e2d321479258993c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 23 Jan 2020 19:34:25 +0100 Subject: [PATCH 05/24] Deprecate SQLLiteral.mapSQL and SQLExpression.sqlLiteral --- GRDB/Core/SQLLiteral.swift | 2 + .../SQL/SQLExpression+QueryInterface.swift | 1 + .../QueryInterfaceExtensibilityTests.swift | 40 ++++++++++++++++++- 3 files changed, 42 insertions(+), 1 deletion(-) diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index 061d10082..f0bbbbbf5 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -16,6 +16,7 @@ public struct SQLLiteral { case expression(SQLExpression) case selectable(SQLSelectable) case orderingTerm(SQLOrderingTerm) + // TODO: remove when the deprecated mapSQL is removed. case map(SQLLiteral, (String) -> String) func sql(_ context: inout SQLGenerationContext) -> String { @@ -88,6 +89,7 @@ public struct SQLLiteral { } /// Returns a literal whose SQL is transformed by the given closure. + @available(*, deprecated, message: "Use SQL interpolation instead") public func mapSQL(_ transform: @escaping (String) -> String) -> SQLLiteral { return SQLLiteral(elements: [.map(self, transform)]) } diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index 38bc53c5a..64fa1f89a 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -6,6 +6,7 @@ extension SQLExpression { /// Converts an expression to an SQLLiteral /// /// :nodoc: + @available(*, deprecated, message: "Use SQL interpolation instead") public var sqlLiteral: SQLLiteral { var context = SQLGenerationContext.literalGenerationContext(withArguments: true) let sql = expressionSQL(&context, wrappedInParenthesis: false) diff --git a/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift b/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift index 7323924c6..6613430ee 100644 --- a/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift @@ -37,7 +37,7 @@ func ~= (_ lhs: SQLExpressible, _ rhs: Column) -> SQLExpression { // CAST -func cast(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression { +func castDeprecated(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression { let literal = value.sqlExpression.sqlLiteral let castLiteral = literal.mapSQL { sql in "CAST(\(sql) AS \(type.rawValue))" @@ -45,6 +45,11 @@ func cast(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpressio return SQLExpressionLiteral(literal: castLiteral) } +#if compiler(>=5.0) +func cast(_ value: T, as type: Database.ColumnType) -> SQLExpression { + return SQLLiteral("CAST(\(value) AS \(sql: type.rawValue))").sqlExpression +} +#endif class QueryInterfaceExtensibilityTests: GRDBTestCase { @@ -87,6 +92,38 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase { } } + func testCastDeprecated() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "records") { t in + t.column("text", .text) + } + struct Record : TableRecord { + static let databaseTableName = "records" + } + + try db.execute(sql: "INSERT INTO records (text) VALUES (?)", arguments: ["foo"]) + + do { + let request = Record.select(castDeprecated(Column("text"), as: .blob)) + let dbValue = try DatabaseValue.fetchOne(db, request)! + switch dbValue.storage { + case .blob: + break + default: + XCTFail("Expected data blob") + } + XCTAssertEqual(self.lastSQLQuery, "SELECT CAST(\"text\" AS BLOB) FROM \"records\" LIMIT 1") + } + do { + let request = Record.select(castDeprecated(Column("text"), as: .blob) && true) + _ = try DatabaseValue.fetchOne(db, request)! + XCTAssertEqual(self.lastSQLQuery, "SELECT (CAST(\"text\" AS BLOB)) AND 1 FROM \"records\" LIMIT 1") + } + } + } + + #if compiler(>=5.0) func testCast() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -117,4 +154,5 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase { } } } + #endif } From 554cbaa307141267632929b1b5c6cf613a7bbde0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 23 Jan 2020 19:46:41 +0100 Subject: [PATCH 06/24] Stop using SQLExpression.sqlLiteral --- Tests/GRDBTests/ColumnExpressionTests.swift | 36 +++++++++------------ 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/Tests/GRDBTests/ColumnExpressionTests.swift b/Tests/GRDBTests/ColumnExpressionTests.swift index 2be27bf96..182a660cc 100644 --- a/Tests/GRDBTests/ColumnExpressionTests.swift +++ b/Tests/GRDBTests/ColumnExpressionTests.swift @@ -66,11 +66,10 @@ class ColumnExpressionTests: GRDBTestCase { try? player.update(db, columns: [Player.Columns.name, Player.Columns.score]) XCTAssertEqual(lastSQLQuery, "UPDATE \"player\" SET \"name\"=\'Arthur\', \"score\"=1000 WHERE \"id\"=1") - // Test FTS3 match expression - let expression = try Player.Columns.name.match(FTS3Pattern(rawPattern: "foo")) - let sqlLiteral = expression.sqlLiteral - XCTAssertEqual(sqlLiteral.sql, "\"name\" MATCH ?") - XCTAssertEqual(sqlLiteral.arguments, ["foo"]) + // Test compound expression + let expression = Player.Columns.name == "foo" + let request = Player.select(expression) + try assertEqualSQL(db, request, "SELECT \"name\" = 'foo' FROM \"player\"") } } @@ -127,11 +126,10 @@ class ColumnExpressionTests: GRDBTestCase { try? player.update(db, columns: [Player.Columns.name, Player.Columns.score]) XCTAssertEqual(lastSQLQuery, "UPDATE \"player\" SET \"name\"=\'Arthur\', \"score\"=1000 WHERE \"id\"=1") - // Test FTS3 match expression - let expression = try Player.Columns.name.match(FTS3Pattern(rawPattern: "foo")) - let sqlLiteral = expression.sqlLiteral - XCTAssertEqual(sqlLiteral.sql, "\"name\" MATCH ?") - XCTAssertEqual(sqlLiteral.arguments, ["foo"]) + // Test compound expression + let expression = Player.Columns.name == "foo" + let request = Player.select(expression) + try assertEqualSQL(db, request, "SELECT \"name\" = 'foo' FROM \"player\"") } } @@ -182,11 +180,10 @@ class ColumnExpressionTests: GRDBTestCase { try? player.update(db, columns: [Player.Columns.name, Player.Columns.score]) XCTAssertEqual(lastSQLQuery, "UPDATE \"player\" SET \"full_name\"=\'Arthur\', \"score\"=1000 WHERE \"id\"=1") - // Test FTS3 match expression - let expression = try Player.Columns.name.match(FTS3Pattern(rawPattern: "foo")) - let sqlLiteral = expression.sqlLiteral - XCTAssertEqual(sqlLiteral.sql, "\"full_name\" MATCH ?") - XCTAssertEqual(sqlLiteral.arguments, ["foo"]) + // Test compound expression + let expression = Player.Columns.name == "foo" + let request = Player.select(expression) + try assertEqualSQL(db, request, "SELECT \"full_name\" = 'foo' FROM \"player\"") } } @@ -231,11 +228,10 @@ class ColumnExpressionTests: GRDBTestCase { try? player.update(db, columns: [Player.CodingKeys.name, Player.CodingKeys.score]) XCTAssertEqual(lastSQLQuery, "UPDATE \"player\" SET \"full_name\"=\'Arthur\', \"score\"=1000 WHERE \"id\"=1") - // Test FTS3 match expression - let expression = try Player.CodingKeys.name.match(FTS3Pattern(rawPattern: "foo")) - let sqlLiteral = expression.sqlLiteral - XCTAssertEqual(sqlLiteral.sql, "\"full_name\" MATCH ?") - XCTAssertEqual(sqlLiteral.arguments, ["foo"]) + // Test compound expression + let expression = Player.CodingKeys.name == "foo" + let request = Player.select(expression) + try assertEqualSQL(db, request, "SELECT \"full_name\" = 'foo' FROM \"player\"") } } } From 86e32cdc234bd425794df51c950aa6031ea99127 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 23 Jan 2020 20:12:49 +0100 Subject: [PATCH 07/24] Cleanup SQLGenerationContext --- GRDB/Core/Database+Statements.swift | 2 +- GRDB/Core/SQLLiteral.swift | 16 +++--- GRDB/Core/SQLRequest.swift | 2 +- .../SQL/SQLExpression+QueryInterface.swift | 6 +-- .../SQLGeneration/SQLGenerationContext.swift | 51 ++++++++++--------- .../SQLGeneration/SQLQueryGenerator.swift | 20 ++++---- GRDB/Record/TableRecord.swift | 2 +- .../GRDBTests/SQLExpressionLiteralTests.swift | 8 +-- 8 files changed, 55 insertions(+), 52 deletions(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 40b8ab1c6..7ff2b5e36 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -165,7 +165,7 @@ extension Database { // // And before we return, we'll check that all arguments were consumed. - var (sql, arguments) = sqlLiteral.sqlWithDefaultContext() + var (sql, arguments) = sqlLiteral.generate() let initialValuesCount = arguments.values.count // Build a C string (SQLite wants that), and execute SQL statements one diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index f0bbbbbf5..351768a34 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -16,10 +16,10 @@ public struct SQLLiteral { case expression(SQLExpression) case selectable(SQLSelectable) case orderingTerm(SQLOrderingTerm) - // TODO: remove when the deprecated mapSQL is removed. + // TODO: remove when the deprecated SQLLiteral.mapSQL(_:) is removed. case map(SQLLiteral, (String) -> String) - func sql(_ context: inout SQLGenerationContext) -> String { + fileprivate func sql(_ context: inout SQLGenerationContext) -> String { switch self { case let .sql(sql, arguments): if context.append(arguments: arguments) == false { @@ -41,7 +41,7 @@ public struct SQLLiteral { } } - func qualified(with alias: TableAlias) -> Element { + fileprivate func qualified(with alias: TableAlias) -> Element { switch self { case .sql: return self @@ -64,11 +64,11 @@ public struct SQLLiteral { } public var sql: String { - return sqlWithDefaultContext().sql + return generate().sql } public var arguments: StatementArguments { - return sqlWithDefaultContext().arguments + return generate().arguments } var elements: [Element] @@ -102,10 +102,10 @@ public struct SQLLiteral { return sql } - func sqlWithDefaultContext() -> (sql: String, arguments: StatementArguments) { - var context = SQLGenerationContext.literalGenerationContext(withArguments: true) + func generate() -> (sql: String, arguments: StatementArguments) { + var context = SQLGenerationContext.sqlLiteralContext let sql = self.sql(&context) - return (sql: sql, arguments: context.arguments!) + return (sql: sql, arguments: context.arguments) } fileprivate func qualified(with alias: TableAlias) -> SQLLiteral { diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index 42c788238..bcf8db971 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -146,7 +146,7 @@ public struct SQLRequest: FetchRequest { /// /// :nodoc: public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { - let (sql, arguments) = sqlLiteral.sqlWithDefaultContext() + let (sql, arguments) = sqlLiteral.generate() let statement: SelectStatement switch cache { case .none: diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index 64fa1f89a..e2944b569 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -8,16 +8,14 @@ extension SQLExpression { /// :nodoc: @available(*, deprecated, message: "Use SQL interpolation instead") public var sqlLiteral: SQLLiteral { - var context = SQLGenerationContext.literalGenerationContext(withArguments: true) - let sql = expressionSQL(&context, wrappedInParenthesis: false) - return SQLLiteral(sql: sql, arguments: context.arguments!) + return SQLLiteral(elements: [.expression(self)]) } /// The expression as a quoted SQL literal (not public in order to avoid abuses) /// /// "foo'bar".databaseValue.quotedSQL() // "'foo''bar'"" func quotedSQL() -> String { - var context = SQLGenerationContext.literalGenerationContext(withArguments: false) + var context = SQLGenerationContext.rawSQLContext return expressionSQL(&context, wrappedInParenthesis: false) } } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index 1924d8d55..ef00aed14 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -5,44 +5,49 @@ /// /// :nodoc: public struct SQLGenerationContext { - var arguments: StatementArguments? + var arguments: StatementArguments { + return _arguments ?? StatementArguments() + } + private var _arguments: StatementArguments? private var resolvedNames: [TableAlias: String] private var qualifierNeeded: Bool - /// Used for SQLExpression -> SQLExpressionLiteral conversion - /// and SQLInterpolation - static func literalGenerationContext(withArguments: Bool) -> SQLGenerationContext { - return SQLGenerationContext( - arguments: withArguments ? [] : nil, - resolvedNames: [:], - qualifierNeeded: false) - } + /// Used for pure SQL generation. Arguments are always empty. + static let rawSQLContext = SQLGenerationContext( + _arguments: nil, + resolvedNames: [:], + qualifierNeeded: false) - /// Used for SQLQuery.makeSelectStatement() and SQLQuery.makeDeleteStatement() - static func queryGenerationContext(aliases: [TableAlias]) -> SQLGenerationContext { + /// Used for SQLLiteral generation + static let sqlLiteralContext = SQLGenerationContext( + _arguments: [], + resolvedNames: [:], + qualifierNeeded: false) + + /// Used for TableRecord.selectionSQL + static let selectionContext = SQLGenerationContext( + _arguments: nil, + resolvedNames: [:], + qualifierNeeded: true) + + /// Used for SQLQueryGenerator + static func queryContext(aliases: [TableAlias]) -> SQLGenerationContext { return SQLGenerationContext( - arguments: [], + _arguments: [], resolvedNames: aliases.resolvedNames, qualifierNeeded: aliases.count > 1) } - /// Used for TableRecord.selectionSQL - static func recordSelectionGenerationContext() -> SQLGenerationContext { - return SQLGenerationContext( - arguments: nil, - resolvedNames: [:], - qualifierNeeded: true) - } - - /// Returns whether arguments could be appended + /// Returns whether arguments could be appended. + /// May be false for SQLGenerationContext.rawSQLContext mutating func append(arguments newArguments: StatementArguments) -> Bool { if newArguments.isEmpty { return true } - guard let arguments = arguments else { + guard let arguments = _arguments else { return false } - self.arguments = arguments + newArguments + self._arguments = arguments + newArguments return true } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 7d9fcb02f..7114af533 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -138,7 +138,7 @@ struct SQLQueryGenerator { return try makeTrivialDeleteStatement(db) } - var context = SQLGenerationContext.queryGenerationContext(aliases: relation.allAliases) + var context = SQLGenerationContext.queryContext(aliases: relation.allAliases) var sql = try "DELETE FROM " + relation.source.sql(db, &context) @@ -156,7 +156,7 @@ struct SQLQueryGenerator { } let statement = try db.makeUpdateStatement(sql: sql) - statement.arguments = context.arguments! + statement.arguments = context.arguments return statement case .unique: @@ -175,7 +175,7 @@ struct SQLQueryGenerator { fatalError("Can't delete without any database table") } - var context = SQLGenerationContext.queryGenerationContext(aliases: relation.allAliases) + var context = SQLGenerationContext.queryContext(aliases: relation.allAliases) // SELECT rowid FROM table ... var generator = self @@ -186,7 +186,7 @@ struct SQLQueryGenerator { let sql = "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE rowid IN (\(selectSQL))" let statement = try db.makeUpdateStatement(sql: sql) - statement.arguments = context.arguments! + statement.arguments = context.arguments return statement } @@ -217,7 +217,7 @@ struct SQLQueryGenerator { return nil } - var context = SQLGenerationContext.queryGenerationContext(aliases: relation.allAliases) + var context = SQLGenerationContext.queryContext(aliases: relation.allAliases) var sql = "UPDATE " @@ -250,7 +250,7 @@ struct SQLQueryGenerator { } let statement = try db.makeUpdateStatement(sql: sql) - statement.arguments = context.arguments! + statement.arguments = context.arguments return statement case .unique: @@ -281,7 +281,7 @@ struct SQLQueryGenerator { return nil } - var context = SQLGenerationContext.queryGenerationContext(aliases: relation.allAliases) + var context = SQLGenerationContext.queryContext(aliases: relation.allAliases) // SELECT rowid FROM table ... var generator = self @@ -307,7 +307,7 @@ struct SQLQueryGenerator { sql += " WHERE rowid IN (\(selectSQL))" let statement = try db.makeUpdateStatement(sql: sql) - statement.arguments = context.arguments! + statement.arguments = context.arguments return statement } @@ -316,14 +316,14 @@ struct SQLQueryGenerator { // Build an SQK generation context with all aliases found in the query, // so that we can disambiguate tables that are used several times with // SQL aliases. - var context = SQLGenerationContext.queryGenerationContext(aliases: relation.allAliases) + var context = SQLGenerationContext.queryContext(aliases: relation.allAliases) // Generate SQL let sql = try self.sql(db, &context) // Compile & set arguments let statement = try db.makeSelectStatement(sql: sql) - statement.arguments = context.arguments! // not nil for this kind of context + statement.arguments = context.arguments // Optimize databaseRegion statement.databaseRegion = try optimizedDatabaseRegion(db, statement.databaseRegion) diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index 5871b2300..8abbf876b 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -130,7 +130,7 @@ extension TableRecord { public static func selectionSQL(alias: String? = nil) -> String { let alias = TableAlias(tableName: databaseTableName, userName: alias) let selection = databaseSelection.map { $0.qualifiedSelectable(with: alias) } - var context = SQLGenerationContext.recordSelectionGenerationContext() + var context = SQLGenerationContext.selectionContext return selection .map { $0.resultColumnSQL(&context) } .joined(separator: ", ") diff --git a/Tests/GRDBTests/SQLExpressionLiteralTests.swift b/Tests/GRDBTests/SQLExpressionLiteralTests.swift index 668b2fdd7..fc79ffa8b 100644 --- a/Tests/GRDBTests/SQLExpressionLiteralTests.swift +++ b/Tests/GRDBTests/SQLExpressionLiteralTests.swift @@ -10,10 +10,10 @@ class SQLExpressionLiteralTests: GRDBTestCase { func testWithArguments() { let expression = Column("foo").collating(.nocase) == "'fooéı👨👨🏿🇫🇷🇨🇮'" && Column("baz") >= 1 - var context = SQLGenerationContext.literalGenerationContext(withArguments: true) + var context = SQLGenerationContext.sqlLiteralContext let sql = expression.expressionSQL(&context, wrappedInParenthesis: true) XCTAssertEqual(sql, "((\"foo\" = ? COLLATE NOCASE) AND (\"baz\" >= ?))") - let values = context.arguments!.values + let values = context.arguments.values XCTAssertEqual(values.count, 2) XCTAssertEqual(values[0], "'fooéı👨👨🏿🇫🇷🇨🇮'".databaseValue) XCTAssertEqual(values[1], 1.databaseValue) @@ -21,9 +21,9 @@ class SQLExpressionLiteralTests: GRDBTestCase { func testWithoutArguments() { let expression = Column("foo").collating(.nocase) == "'fooéı👨👨🏿🇫🇷🇨🇮'" && Column("baz") >= 1 - var context = SQLGenerationContext.literalGenerationContext(withArguments: false) + var context = SQLGenerationContext.rawSQLContext let sql = expression.expressionSQL(&context, wrappedInParenthesis: true) - XCTAssertNil(context.arguments) + XCTAssert(context.arguments.isEmpty) XCTAssertEqual(sql, "((\"foo\" = '''fooéı👨👨🏿🇫🇷🇨🇮''' COLLATE NOCASE) AND (\"baz\" >= 1))") } } From 812f30fb75d3ab770a637d4ada882a412a094b23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 23 Jan 2020 20:22:05 +0100 Subject: [PATCH 08/24] Remove SQLLiteral.generate() --- GRDB/Core/Database+Statements.swift | 4 +++- GRDB/Core/SQLLiteral.swift | 15 +++++++-------- GRDB/Core/SQLRequest.swift | 5 +++-- 3 files changed, 13 insertions(+), 11 deletions(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 7ff2b5e36..8c6515b7c 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -165,7 +165,9 @@ extension Database { // // And before we return, we'll check that all arguments were consumed. - var (sql, arguments) = sqlLiteral.generate() + var context = SQLGenerationContext.sqlLiteralContext + let sql = sqlLiteral.sql(&context) + var arguments = context.arguments let initialValuesCount = arguments.values.count // Build a C string (SQLite wants that), and execute SQL statements one diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index 351768a34..77d574b0c 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -10,6 +10,8 @@ /// try db.execute(literal: query) /// } public struct SQLLiteral { + /// SQLLiteral is an array of elements which can be qualified with + /// table aliases. enum Element { case sql(String, StatementArguments = StatementArguments()) case sqlLiteral(SQLLiteral, qualified: Bool = false) @@ -64,11 +66,14 @@ public struct SQLLiteral { } public var sql: String { - return generate().sql + var context = SQLGenerationContext.sqlLiteralContext + return sql(&context) } public var arguments: StatementArguments { - return generate().arguments + var context = SQLGenerationContext.sqlLiteralContext + _ = sql(&context) + return context.arguments } var elements: [Element] @@ -102,12 +107,6 @@ public struct SQLLiteral { return sql } - func generate() -> (sql: String, arguments: StatementArguments) { - var context = SQLGenerationContext.sqlLiteralContext - let sql = self.sql(&context) - return (sql: sql, arguments: context.arguments) - } - fileprivate func qualified(with alias: TableAlias) -> SQLLiteral { return SQLLiteral(elements: elements.map { $0.qualified(with: alias) }) } diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index bcf8db971..0d7b5ac8c 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -146,7 +146,8 @@ public struct SQLRequest: FetchRequest { /// /// :nodoc: public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { - let (sql, arguments) = sqlLiteral.generate() + var context = SQLGenerationContext.sqlLiteralContext + let sql = sqlLiteral.sql(&context) let statement: SelectStatement switch cache { case .none: @@ -156,7 +157,7 @@ public struct SQLRequest: FetchRequest { case .internal?: statement = try db.internalCachedSelectStatement(sql: sql) } - try statement.setArgumentsWithValidation(arguments) + try statement.setArgumentsWithValidation(context.arguments) return PreparedRequest(statement: statement, adapter: adapter) } } From 7f513cbc1d3facd5b9b5d50a0de658595ef06325 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 23 Jan 2020 20:27:53 +0100 Subject: [PATCH 09/24] SQLLiteral cleanup --- GRDB/Core/SQLLiteral.swift | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index 77d574b0c..e814899e3 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -179,14 +179,12 @@ extension Sequence where Element == SQLLiteral { /// ] /// let query = components.joined(separator: " ") public func joined(separator: String = "") -> SQLLiteral { - // Calling the two properties `sql` and `arguments` must not consume the - // sequence twice, or we would get inconsistent values if the sequence - // does not yield the same elements on the two distinct iterations. - // So let's turn the sequence into a collection first. - // - // TODO: consider deprecating the two `sql` and `arguments` properties, - // and provide a more efficient implementation of this method. - return Array(self).joined(separator: separator) + if separator.isEmpty { + return SQLLiteral(elements: flatMap { $0.elements }) + } else { + let separator = SQLLiteral.Element.sql(separator) + return SQLLiteral(elements: Array(map { $0.elements }.joined(separator: CollectionOfOne(separator)))) + } } } @@ -202,7 +200,7 @@ extension Collection where Element == SQLLiteral { /// let query = components.joined(separator: " ") public func joined(separator: String = "") -> SQLLiteral { if separator.isEmpty { - return SQLLiteral(elements: Array(map { $0.elements }.joined())) + return SQLLiteral(elements: flatMap { $0.elements }) } else { let separator = SQLLiteral.Element.sql(separator) return SQLLiteral(elements: Array(map { $0.elements }.joined(separator: CollectionOfOne(separator)))) From 2d3a9991d43993154a26024066ae190b58d53ea9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 23 Jan 2020 21:00:39 +0100 Subject: [PATCH 10/24] Test documented use case --- Tests/GRDBTests/SQLLiteralTests.swift | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Tests/GRDBTests/SQLLiteralTests.swift b/Tests/GRDBTests/SQLLiteralTests.swift index 0210a9d1e..9d92188b5 100644 --- a/Tests/GRDBTests/SQLLiteralTests.swift +++ b/Tests/GRDBTests/SQLLiteralTests.swift @@ -402,6 +402,7 @@ extension SQLLiteralTests { try makeDatabaseQueue().write { db in try db.create(table: "player") { t in t.column("name", .text) + t.column("createdAt", .datetime) } let nameColumn = Column("name") let baseRequest = Player.aliased(TableAlias(name: "p")) @@ -430,6 +431,17 @@ extension SQLLiteralTests { SELECT "p".* FROM "player" "p" WHERE "p"."name" = (SELECT MAX("name") FROM "player") """) } + + do { + // Test of documentation + let date = "2020-01-23" + let createdAt = Column("createdAt") + let creationDate = SQLLiteral("DATE(\(createdAt))").sqlExpression + let request = Player.filter(creationDate == date) + try assertEqualSQL(db, request, """ + SELECT * FROM "player" WHERE (DATE("createdAt")) = '2020-01-23' + """) + } } } } From ddd22a1dfbc85cb0dfa0f182238b630bc1d4c4c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 24 Jan 2020 09:00:51 +0100 Subject: [PATCH 11/24] Restore Swift 4.2 by default --- GRDB.xcodeproj/project.pbxproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index d8d1a9881..1330609dc 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -4295,7 +4295,7 @@ MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 5.0; + SWIFT_VERSION = 4.2; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; @@ -4343,7 +4343,7 @@ GCC_WARN_UNUSED_VARIABLE = YES; MTL_ENABLE_DEBUG_INFO = NO; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; - SWIFT_VERSION = 5.0; + SWIFT_VERSION = 4.2; VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; From b8c5af5cef873188de3aee076140f5c8ea796f53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 24 Jan 2020 09:03:06 +0100 Subject: [PATCH 12/24] Fix availability test --- Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift b/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift index 6613430ee..97a4bf0ee 100644 --- a/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift @@ -45,7 +45,7 @@ func castDeprecated(_ value: SQLExpressible, as type: Database.ColumnType) -> SQ return SQLExpressionLiteral(literal: castLiteral) } -#if compiler(>=5.0) +#if swift(>=5.0) func cast(_ value: T, as type: Database.ColumnType) -> SQLExpression { return SQLLiteral("CAST(\(value) AS \(sql: type.rawValue))").sqlExpression } @@ -123,7 +123,7 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase { } } - #if compiler(>=5.0) + #if swift(>=5.0) func testCast() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in From e2545b34272c5d63a421535ffa1c211399179cec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 25 Jan 2020 12:15:14 +0100 Subject: [PATCH 13/24] Test for more complex SQLLiteral generation --- GRDB/Core/SQLInterpolation.swift | 2 +- GRDB/Core/SQLLiteral.swift | 22 ++++++++++++++----- .../SQLInterpolation+QueryInterface.swift | 2 +- Tests/GRDBTests/SQLLiteralTests.swift | 11 ++++++++++ 4 files changed, 29 insertions(+), 8 deletions(-) diff --git a/GRDB/Core/SQLInterpolation.swift b/GRDB/Core/SQLInterpolation.swift index a43ecb3af..ad2ea3d8b 100644 --- a/GRDB/Core/SQLInterpolation.swift +++ b/GRDB/Core/SQLInterpolation.swift @@ -20,7 +20,7 @@ public struct SQLInterpolation: StringInterpolationProtocol { /// "SELECT * FROM player WHERE \(literal: condition)" public mutating func appendInterpolation(literal sqlLiteral: SQLLiteral) { - elements.append(.sqlLiteral(sqlLiteral)) + elements.append(.literal(sqlLiteral, qualifierLocked: false)) } } #endif diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index e814899e3..0a677758d 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -13,14 +13,19 @@ public struct SQLLiteral { /// SQLLiteral is an array of elements which can be qualified with /// table aliases. enum Element { - case sql(String, StatementArguments = StatementArguments()) - case sqlLiteral(SQLLiteral, qualified: Bool = false) + case sql(String, StatementArguments) + case literal(SQLLiteral, qualifierLocked: Bool) case expression(SQLExpression) case selectable(SQLSelectable) case orderingTerm(SQLOrderingTerm) // TODO: remove when the deprecated SQLLiteral.mapSQL(_:) is removed. case map(SQLLiteral, (String) -> String) + // TODO: remove and use default case argument when compiler >= 5.1 + static func sql(_ sql: String) -> Element { + return .sql(sql, StatementArguments()) + } + fileprivate func sql(_ context: inout SQLGenerationContext) -> String { switch self { case let .sql(sql, arguments): @@ -30,7 +35,7 @@ public struct SQLLiteral { fatalError("Not implemented") } return sql - case let .sqlLiteral(sqlLiteral, _): + case let .literal(sqlLiteral, _): return sqlLiteral.sql(&context) case let .expression(expression): return expression.expressionSQL(&context, wrappedInParenthesis: false) @@ -47,11 +52,11 @@ public struct SQLLiteral { switch self { case .sql: return self - case let .sqlLiteral(sqlLiteral, qualified): - if qualified { + case let .literal(sqlLiteral, qualifierLocked): + if qualifierLocked { return self } else { - return .sqlLiteral(sqlLiteral.qualified(with: alias), qualified: false /* allow requalification */) + return .literal(sqlLiteral.qualified(with: alias), qualifierLocked: false) } case let .expression(expression): return .expression(expression.qualifiedExpression(with: alias)) @@ -93,6 +98,11 @@ public struct SQLLiteral { self.init(elements: [.sql(sql, arguments)]) } + /// TODO + public init(_ expressible: SQLExpressible) { + self.init(elements: [.expression(expressible.sqlExpression)]) + } + /// Returns a literal whose SQL is transformed by the given closure. @available(*, deprecated, message: "Use SQL interpolation instead") public func mapSQL(_ transform: @escaping (String) -> String) -> SQLLiteral { diff --git a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift index 44dd55618..04f3e10ab 100644 --- a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift @@ -148,7 +148,7 @@ extension SQLInterpolation { /// """ public mutating func appendInterpolation(_ request: SQLRequest) { appendLiteral("(") - elements.append(.sqlLiteral(request.sqlLiteral, qualified: true /* don't requalify */)) + elements.append(.literal(request.sqlLiteral, qualifierLocked: true)) appendLiteral(")") } } diff --git a/Tests/GRDBTests/SQLLiteralTests.swift b/Tests/GRDBTests/SQLLiteralTests.swift index 9d92188b5..da8ad41d5 100644 --- a/Tests/GRDBTests/SQLLiteralTests.swift +++ b/Tests/GRDBTests/SQLLiteralTests.swift @@ -432,6 +432,17 @@ extension SQLLiteralTests { """) } + do { + let concatenation = [nameColumn, "O'Brien", nameColumn] + .map { (expressible: SQLExpressible) in SQLLiteral(expressible) } + .joined(separator: " || ") + .sqlExpression + let request = baseRequest.select(concatenation) + try assertEqualSQL(db, request, """ + SELECT "p"."name" || 'O''Brien' || "p"."name" FROM "player" "p" + """) + } + do { // Test of documentation let date = "2020-01-23" From db8585aa853a40c8ad6c78c554a11f22302b705f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 25 Jan 2020 12:34:22 +0100 Subject: [PATCH 14/24] Test for SQLLiteral(expression) --- GRDB/Core/SQLLiteral.swift | 14 +++++++-- Tests/GRDBTests/SQLLiteralTests.swift | 45 ++++++++++++++++----------- 2 files changed, 38 insertions(+), 21 deletions(-) diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index 0a677758d..5f2f6ad43 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -98,9 +98,17 @@ public struct SQLLiteral { self.init(elements: [.sql(sql, arguments)]) } - /// TODO - public init(_ expressible: SQLExpressible) { - self.init(elements: [.expression(expressible.sqlExpression)]) + /// Creates an SQLLiteral from an SQL expression. + /// + /// For example: + /// + /// let columnLiteral = SQLLiteral(Column("username")) + /// let suffixLiteral = SQLLiteral("@example.com".databaseValue) + /// let emailLiteral = [columnLiteral, suffixLiteral].joined(separator: " || ") + /// let request = User.select(emailLiteral.sqlExpression) + /// let emails = try String.fetchAll(db, request) + public init(_ expression: SQLExpression) { + self.init(elements: [.expression(expression)]) } /// Returns a literal whose SQL is transformed by the given closure. diff --git a/Tests/GRDBTests/SQLLiteralTests.swift b/Tests/GRDBTests/SQLLiteralTests.swift index da8ad41d5..c3e058b56 100644 --- a/Tests/GRDBTests/SQLLiteralTests.swift +++ b/Tests/GRDBTests/SQLLiteralTests.swift @@ -108,6 +108,25 @@ class SQLLiteralTests: GRDBTestCase { XCTAssertEqual(joined.arguments, [1000] + ["name": "Arthur"]) } } + + func testQualifiedSQLLiteral() throws { + struct Player: TableRecord { } + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("createdAt", .datetime) + } + + // Test of SQLLiteral.init(_:) documentation (plus qualification) + let columnLiteral = SQLLiteral(Column("name")) + let suffixLiteral = SQLLiteral("O''Brien".databaseValue) + let literal = [columnLiteral, suffixLiteral].joined(separator: " || ") + let request = Player.aliased(TableAlias(name: "p")).select(literal.sqlExpression) + try assertEqualSQL(db, request, """ + SELECT "p"."name" || 'O''''Brien' FROM "player" "p" + """) + } + } } #if swift(>=5.0) @@ -397,7 +416,7 @@ extension SQLLiteralTests { XCTAssertEqual(query.arguments, ["name": "Arthur"]) } - func testQualifiedSQLLiteral() throws { + func testQualifiedSQLInterpolation() throws { struct Player: TableRecord { } try makeDatabaseQueue().write { db in try db.create(table: "player") { t in @@ -407,42 +426,32 @@ extension SQLLiteralTests { let nameColumn = Column("name") let baseRequest = Player.aliased(TableAlias(name: "p")) - let alteredNameLiteral = SQLLiteral("\(nameColumn) || \("foo")") do { + let alteredNameLiteral = SQLLiteral("\(nameColumn) || \("O'Brien")") let request = baseRequest.select(literal: alteredNameLiteral) try assertEqualSQL(db, request, """ - SELECT "p"."name" || 'foo' FROM "player" "p" + SELECT "p"."name" || 'O''Brien' FROM "player" "p" """) } - let alteredNameColumn = alteredNameLiteral.sqlExpression.forKey("alteredName") do { + let alteredNameLiteral = SQLLiteral("\(nameColumn) || \("O'Brien")") + let alteredNameColumn = alteredNameLiteral.sqlExpression.forKey("alteredName") let request = baseRequest.select(alteredNameColumn) try assertEqualSQL(db, request, """ - SELECT "p"."name" || 'foo' AS "alteredName" FROM "player" "p" + SELECT "p"."name" || 'O''Brien' AS "alteredName" FROM "player" "p" """) } - let subQuery: SQLRequest = "SELECT MAX(\(nameColumn)) FROM \(Player.self)" - let conditionLiteral = SQLLiteral("\(nameColumn) = \(subQuery)") do { + let subQuery: SQLRequest = "SELECT MAX(\(nameColumn)) FROM \(Player.self)" + let conditionLiteral = SQLLiteral("\(nameColumn) = \(subQuery)") let request = baseRequest.filter(literal: conditionLiteral) try assertEqualSQL(db, request, """ SELECT "p".* FROM "player" "p" WHERE "p"."name" = (SELECT MAX("name") FROM "player") """) } - do { - let concatenation = [nameColumn, "O'Brien", nameColumn] - .map { (expressible: SQLExpressible) in SQLLiteral(expressible) } - .joined(separator: " || ") - .sqlExpression - let request = baseRequest.select(concatenation) - try assertEqualSQL(db, request, """ - SELECT "p"."name" || 'O''Brien' || "p"."name" FROM "player" "p" - """) - } - do { // Test of documentation let date = "2020-01-23" From e999ab5ecb7368d041782206a5a3abaedff280fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 25 Jan 2020 13:46:00 +0100 Subject: [PATCH 15/24] Don't deprecate SQLLiteral.mapSQL, after all --- GRDB/Core/SQLLiteral.swift | 2 +- .../SQL/SQLExpression+QueryInterface.swift | 2 +- .../QueryInterfaceExtensibilityTests.swift | 43 +++++++++++++++++-- 3 files changed, 42 insertions(+), 5 deletions(-) diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index 5f2f6ad43..8aad4ef23 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -111,8 +111,8 @@ public struct SQLLiteral { self.init(elements: [.expression(expression)]) } + // TODO: deprecate when SQL interpolation is always available /// Returns a literal whose SQL is transformed by the given closure. - @available(*, deprecated, message: "Use SQL interpolation instead") public func mapSQL(_ transform: @escaping (String) -> String) -> SQLLiteral { return SQLLiteral(elements: [.map(self, transform)]) } diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index e2944b569..3e7349a88 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -6,7 +6,7 @@ extension SQLExpression { /// Converts an expression to an SQLLiteral /// /// :nodoc: - @available(*, deprecated, message: "Use SQL interpolation instead") + @available(*, deprecated, message: "Use SQLLiteral initializer instead") public var sqlLiteral: SQLLiteral { return SQLLiteral(elements: [.expression(self)]) } diff --git a/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift b/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift index 97a4bf0ee..a93e741e5 100644 --- a/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift @@ -37,7 +37,7 @@ func ~= (_ lhs: SQLExpressible, _ rhs: Column) -> SQLExpression { // CAST -func castDeprecated(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression { +private func castDeprecated(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression { let literal = value.sqlExpression.sqlLiteral let castLiteral = literal.mapSQL { sql in "CAST(\(sql) AS \(type.rawValue))" @@ -45,8 +45,14 @@ func castDeprecated(_ value: SQLExpressible, as type: Database.ColumnType) -> SQ return SQLExpressionLiteral(literal: castLiteral) } +private func cast(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression { + return SQLLiteral(value.sqlExpression) + .mapSQL({ sql in "CAST(\(sql) AS \(type.rawValue))" }) + .sqlExpression +} + #if swift(>=5.0) -func cast(_ value: T, as type: Database.ColumnType) -> SQLExpression { +private func castInterpolated(_ value: T, as type: Database.ColumnType) -> SQLExpression { return SQLLiteral("CAST(\(value) AS \(sql: type.rawValue))").sqlExpression } #endif @@ -123,7 +129,6 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase { } } - #if swift(>=5.0) func testCast() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -154,5 +159,37 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase { } } } + + #if swift(>=5.0) + func testCastInterpolated() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "records") { t in + t.column("text", .text) + } + struct Record : TableRecord { + static let databaseTableName = "records" + } + + try db.execute(sql: "INSERT INTO records (text) VALUES (?)", arguments: ["foo"]) + + do { + let request = Record.select(castInterpolated(Column("text"), as: .blob)) + let dbValue = try DatabaseValue.fetchOne(db, request)! + switch dbValue.storage { + case .blob: + break + default: + XCTFail("Expected data blob") + } + XCTAssertEqual(self.lastSQLQuery, "SELECT CAST(\"text\" AS BLOB) FROM \"records\" LIMIT 1") + } + do { + let request = Record.select(castInterpolated(Column("text"), as: .blob) && true) + _ = try DatabaseValue.fetchOne(db, request)! + XCTAssertEqual(self.lastSQLQuery, "SELECT (CAST(\"text\" AS BLOB)) AND 1 FROM \"records\" LIMIT 1") + } + } + } #endif } From d448bd8bd55e55995f86aa8505fe8f1abcf2b85d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 25 Jan 2020 14:32:13 +0100 Subject: [PATCH 16/24] Test SQLLiteral.mapSQL qualification --- Tests/GRDBTests/SQLLiteralTests.swift | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/Tests/GRDBTests/SQLLiteralTests.swift b/Tests/GRDBTests/SQLLiteralTests.swift index c3e058b56..ddb3c3278 100644 --- a/Tests/GRDBTests/SQLLiteralTests.swift +++ b/Tests/GRDBTests/SQLLiteralTests.swift @@ -117,14 +117,25 @@ class SQLLiteralTests: GRDBTestCase { t.column("createdAt", .datetime) } - // Test of SQLLiteral.init(_:) documentation (plus qualification) - let columnLiteral = SQLLiteral(Column("name")) - let suffixLiteral = SQLLiteral("O''Brien".databaseValue) - let literal = [columnLiteral, suffixLiteral].joined(separator: " || ") - let request = Player.aliased(TableAlias(name: "p")).select(literal.sqlExpression) - try assertEqualSQL(db, request, """ - SELECT "p"."name" || 'O''''Brien' FROM "player" "p" - """) + do { + // Test of SQLLiteral.init(_:) documentation (plus qualification) + let columnLiteral = SQLLiteral(Column("name")) + let suffixLiteral = SQLLiteral("O'Brien".databaseValue) + let literal = [columnLiteral, suffixLiteral].joined(separator: " || ") + let request = Player.aliased(TableAlias(name: "p")).select(literal.sqlExpression) + try assertEqualSQL(db, request, """ + SELECT "p"."name" || 'O''Brien' FROM "player" "p" + """) + } + + do { + // Test mapSQL plus qualification + let literal = SQLLiteral(Column("name")).mapSQL { sql in "\(sql) || 'foo'" } + let request = Player.aliased(TableAlias(name: "p")).select(literal.sqlExpression) + try assertEqualSQL(db, request, """ + SELECT "p"."name" || 'foo' FROM "player" "p" + """) + } } } } From e4c6029e721d8817335a03e23e96381d7e4834f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 25 Jan 2020 14:37:00 +0100 Subject: [PATCH 17/24] Cleanup internal APIs --- GRDB/Core/SQLLiteral.swift | 2 +- GRDB/Core/SQLRequest.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index 8aad4ef23..8d455ef1b 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -81,7 +81,7 @@ public struct SQLLiteral { return context.arguments } - var elements: [Element] + private(set) var elements: [Element] init(elements: [Element]) { self.elements = elements diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index 0d7b5ac8c..74c76903d 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -31,7 +31,7 @@ public struct SQLRequest: FetchRequest { /// The request adapter public var adapter: RowAdapter? - var sqlLiteral: SQLLiteral + private(set) var sqlLiteral: SQLLiteral private let cache: Cache? /// Creates a request from an SQL string, optional arguments, and From 3ccfcb61ced36cdf156f882e868fe81d1a9c8231 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 25 Jan 2020 16:11:17 +0100 Subject: [PATCH 18/24] Cleanup SQLLiteral elements --- GRDB/Core/SQLInterpolation.swift | 2 +- GRDB/Core/SQLLiteral.swift | 15 ++++++--------- .../SQLInterpolation+QueryInterface.swift | 4 +--- 3 files changed, 8 insertions(+), 13 deletions(-) diff --git a/GRDB/Core/SQLInterpolation.swift b/GRDB/Core/SQLInterpolation.swift index ad2ea3d8b..695c93aba 100644 --- a/GRDB/Core/SQLInterpolation.swift +++ b/GRDB/Core/SQLInterpolation.swift @@ -20,7 +20,7 @@ public struct SQLInterpolation: StringInterpolationProtocol { /// "SELECT * FROM player WHERE \(literal: condition)" public mutating func appendInterpolation(literal sqlLiteral: SQLLiteral) { - elements.append(.literal(sqlLiteral, qualifierLocked: false)) + elements.append(contentsOf: sqlLiteral.elements) } } #endif diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index 8d455ef1b..6d25b3229 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -14,10 +14,10 @@ public struct SQLLiteral { /// table aliases. enum Element { case sql(String, StatementArguments) - case literal(SQLLiteral, qualifierLocked: Bool) case expression(SQLExpression) case selectable(SQLSelectable) case orderingTerm(SQLOrderingTerm) + case subQuery(SQLLiteral) // TODO: remove when the deprecated SQLLiteral.mapSQL(_:) is removed. case map(SQLLiteral, (String) -> String) @@ -35,14 +35,14 @@ public struct SQLLiteral { fatalError("Not implemented") } return sql - case let .literal(sqlLiteral, _): - return sqlLiteral.sql(&context) case let .expression(expression): return expression.expressionSQL(&context, wrappedInParenthesis: false) case let .selectable(selectable): return selectable.resultColumnSQL(&context) case let .orderingTerm(orderingTerm): return orderingTerm.orderingTermSQL(&context) + case let .subQuery(sqlLiteral): + return "(" + sqlLiteral.sql(&context) + ")" case let .map(sqlLiteral, transform): return transform(sqlLiteral.sql(&context)) } @@ -52,18 +52,15 @@ public struct SQLLiteral { switch self { case .sql: return self - case let .literal(sqlLiteral, qualifierLocked): - if qualifierLocked { - return self - } else { - return .literal(sqlLiteral.qualified(with: alias), qualifierLocked: false) - } case let .expression(expression): return .expression(expression.qualifiedExpression(with: alias)) case let .selectable(selectable): return .selectable(selectable.qualifiedSelectable(with: alias)) case let .orderingTerm(orderingTerm): return .orderingTerm(orderingTerm.qualifiedOrdering(with: alias)) + case .subQuery: + // subqueries are not requalified + return self case let .map(sqlLiteral, transform): return .map(sqlLiteral.qualified(with: alias), transform) } diff --git a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift index 04f3e10ab..9320d24c5 100644 --- a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift @@ -147,9 +147,7 @@ extension SQLInterpolation { /// SELECT * FROM player WHERE score = \(subQuery) /// """ public mutating func appendInterpolation(_ request: SQLRequest) { - appendLiteral("(") - elements.append(.literal(request.sqlLiteral, qualifierLocked: true)) - appendLiteral(")") + elements.append(.subQuery(request.sqlLiteral)) } } #endif From c64b2d1032c7f15e5f3e0770189722ec576aea93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 25 Jan 2020 16:18:12 +0100 Subject: [PATCH 19/24] Cleanup --- GRDB/Core/SQLLiteral.swift | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index 6d25b3229..c10986966 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -197,15 +197,14 @@ extension Sequence where Element == SQLLiteral { if separator.isEmpty { return SQLLiteral(elements: flatMap { $0.elements }) } else { - let separator = SQLLiteral.Element.sql(separator) - return SQLLiteral(elements: Array(map { $0.elements }.joined(separator: CollectionOfOne(separator)))) + return SQLLiteral(elements: Array(map { $0.elements }.joined(separator: CollectionOfOne(.sql(separator))))) } } } extension Collection where Element == SQLLiteral { /// Returns the concatenated SQLLiteral of this collection of literals, - /// inserting the given separator between each element. + /// inserting the given SQL separator between each element. /// /// let components: [SQLLiteral] = [ /// "UPDATE player", @@ -217,8 +216,7 @@ extension Collection where Element == SQLLiteral { if separator.isEmpty { return SQLLiteral(elements: flatMap { $0.elements }) } else { - let separator = SQLLiteral.Element.sql(separator) - return SQLLiteral(elements: Array(map { $0.elements }.joined(separator: CollectionOfOne(separator)))) + return SQLLiteral(elements: Array(map { $0.elements }.joined(separator: CollectionOfOne(.sql(separator))))) } } } From b961962f9315c91a555331259b1db15ce1cb3c19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 25 Jan 2020 16:29:04 +0100 Subject: [PATCH 20/24] Cleanup --- GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index 3e7349a88..34e432094 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -8,7 +8,7 @@ extension SQLExpression { /// :nodoc: @available(*, deprecated, message: "Use SQLLiteral initializer instead") public var sqlLiteral: SQLLiteral { - return SQLLiteral(elements: [.expression(self)]) + return SQLLiteral(self) } /// The expression as a quoted SQL literal (not public in order to avoid abuses) From 591384576f92da7ab2e3a4b2eab684e3b14f349d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 14 Feb 2020 12:31:54 +0100 Subject: [PATCH 21/24] SQLOrderingLiteral (and prevent reversing of requests ordered by literal) --- GRDB/Core/SQLLiteral.swift | 30 +++++++++++++++++++ .../Request/RequestProtocols.swift | 2 +- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index c10986966..90eb1a986 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -181,6 +181,10 @@ extension SQLLiteral { var sqlSelectable: SQLSelectable { return SQLSelectionLiteral(sqlLiteral: self) } + + var sqlOrderingTerm: SQLOrderingTerm { + return SQLOrderingLiteral(sqlLiteral: self) + } } extension Sequence where Element == SQLLiteral { @@ -355,3 +359,29 @@ private struct SQLSelectionLiteral: SQLSelectable { return sqlLiteral.qualified(with: alias).sqlSelectable } } + +// MARK: - SQLOrderingLiteral + +private struct SQLOrderingLiteral: SQLOrderingTerm { + private let sqlLiteral: SQLLiteral + + // Prefer SQLLiteral.sqlOrderingTerm + fileprivate init(sqlLiteral: SQLLiteral) { + self.sqlLiteral = sqlLiteral + } + + var reversed: SQLOrderingTerm { + fatalError(""" + Ordering literals can't be reversed. \ + To resolve this error, order by expression literals instead. + """) + } + + func orderingTermSQL(_ context: inout SQLGenerationContext) -> String { + return sqlLiteral.sql(&context) + } + + func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { + return sqlLiteral.qualified(with: alias).sqlOrderingTerm + } +} diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 672d221b4..043f9fd6e 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -496,7 +496,7 @@ extension OrderedRequest { /// .order(sql: "name") public func order(literal sqlLiteral: SQLLiteral) -> Self { // NOT TESTED - return order(sqlLiteral.sqlExpression) + return order(sqlLiteral.sqlOrderingTerm) } } From 8c3274bd3cd2e3037fdf0fc9a6052d84d646c24d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 14 Feb 2020 12:36:36 +0100 Subject: [PATCH 22/24] Cleanup --- GRDB/Core/SQLLiteral.swift | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index 90eb1a986..1be459d4c 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -115,11 +115,7 @@ public struct SQLLiteral { } func sql(_ context: inout SQLGenerationContext) -> String { - var sql = "" - for element in elements { - sql += element.sql(&context) - } - return sql + return elements.map { $0.sql(&context) }.joined() } fileprivate func qualified(with alias: TableAlias) -> SQLLiteral { From 355ae49bc298431726de6aa6f3e97992f812a855 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 14 Feb 2020 12:46:01 +0100 Subject: [PATCH 23/24] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e1610799..922570329 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -65,6 +65,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: **New** - [#689](https://github.com/groue/GRDB.swift/pull/689) by [@gjeck](https://github.com/gjeck): Add support for renaming columns within a table +- [#690](https://github.com/groue/GRDB.swift/pull/690): Enhance SQLLiteral and SQL interpolation ## 4.9.0 From 1b8511ab517c815acb4c9f7d99cd30a2d4f55422 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 14 Feb 2020 12:59:06 +0100 Subject: [PATCH 24/24] Documentation --- Documentation/SQLInterpolation.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/Documentation/SQLInterpolation.md b/Documentation/SQLInterpolation.md index 571a95e13..a9fae482e 100644 --- a/Documentation/SQLInterpolation.md +++ b/Documentation/SQLInterpolation.md @@ -22,6 +22,7 @@ SQL Interpolation is an answer to these troubles. It is available in Swift 5. - [Introduction] - [SQLLiteral] +- [SQL Interpolation and the Query Interface] - [SQL Interpolation and Record Protocols] - [SQL Interpolation Reference] @@ -127,6 +128,23 @@ let query = SQLLiteral( SQLLiteral can embed any [value], as we have seen above, but not only. Please keep on reading the next chapter, or jump directly to the [SQL Interpolation Reference]. +## SQL Interpolation and the Query Interface + +SQL Interpolation and SQLLiteral let you embed raw SQL snippets in [query interface requests]. + +For example: + +```swift +// SELECT * FROM player WHERE name = 'O''Brien' +let request = Player.filter(literal: "name = \("O'Brien")") + +// SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23' +let createdAt = Column("createdAt") +let creationDay = SQLLiteral("DATE(\(createdAt))").sqlExpression +let request = Player.filter(creationDay == "2020-01-23") +``` + + ## SQL Interpolation and Record Protocols The [record protocols] extend your application types with database abilities. @@ -399,6 +417,7 @@ This chapter lists all kinds of supported interpolations. [Introduction]: #introduction [SQLLiteral]: #sqlliteral +[SQL Interpolation and the Query Interface]: #sql-interpolation-and-the-query-interface [SQL Interpolation and Record Protocols]: #sql-interpolation-and-record-protocols [SQL Interpolation Reference]: #sql-interpolation-reference [String interpolation]: https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html#ID292 @@ -415,4 +434,5 @@ This chapter lists all kinds of supported interpolations. [record]: ../README.md#records [Expressions]: ../README.md#expressions [welcomed]: ../README.md#sqlite-api +[query interface requests]: ../README.md#requests [SE-0228 Fix ExpressibleByStringInterpolation]: https://github.com/apple/swift-evolution/blob/master/proposals/0228-fix-expressiblebystringinterpolation.md