Merge pull request #690 from groue/dev/qualifiedSQLLiteral

Enhance SQLLiteral and SQL interpolation
This commit is contained in:
Gwendal Roué authored and GitHub committed 2020-02-15 09:34:23 +01:00
commit 3379bf3b08
24 files changed
+551 -494

No files matched your search

+1
View File
@@ -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
+20
View File
@@ -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
+2 -10
View File
@@ -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 = "<group>"; };
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = "<group>"; };
567ECE4E2222E431009245CA /* GRDB-4.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "GRDB-4.0.swift"; sourceTree = "<group>"; };
567F0B2C220F0E2E00D111FB /* SQLInterpolationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLInterpolationTests.swift; sourceTree = "<group>"; };
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = "<group>"; };
@@ -2081,7 +2077,6 @@
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */,
56A2381D1B9C74A90082EB20 /* Row */,
569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */,
567F0B2C220F0E2E00D111FB /* SQLInterpolationTests.swift */,
56B86E72220FF4E000524C16 /* SQLLiteralTests.swift */,
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */,
56A238201B9C74A90082EB20 /* Statement */,
@@ -2559,11 +2554,11 @@
};
56E5D7C91B4D3FED00430942 = {
CreatedOnToolsVersion = 7.0;
LastSwiftMigration = 1020;
LastSwiftMigration = 1130;
};
56E5D7D21B4D3FEE00430942 = {
CreatedOnToolsVersion = 7.0;
LastSwiftMigration = 0800;
LastSwiftMigration = 1130;
ProvisioningStyle = Manual;
};
56E5D7F81B4D422D00430942 = {
@@ -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 */,
+4 -2
View File
@@ -165,12 +165,14 @@ extension Database {
//
// And before we return, we'll check that all arguments were consumed.
var arguments = sqlLiteral.arguments
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
// 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
+6 -13
View File
@@ -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(contentsOf: sqlLiteral.elements)
}
}
#endif
+264 -27
View File
@@ -10,8 +10,79 @@
/// try db.execute(literal: query)
/// }
public struct SQLLiteral {
public private(set) var sql: String
public private(set) var arguments: StatementArguments
/// SQLLiteral is an array of elements which can be qualified with
/// table aliases.
enum Element {
case sql(String, StatementArguments)
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)
// 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):
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 .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))
}
}
fileprivate func qualified(with alias: TableAlias) -> Element {
switch self {
case .sql:
return self
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)
}
}
}
public var sql: String {
var context = SQLGenerationContext.sqlLiteralContext
return sql(&context)
}
public var arguments: StatementArguments {
var context = SQLGenerationContext.sqlLiteralContext
_ = sql(&context)
return context.arguments
}
private(set) var elements: [Element]
init(elements: [Element]) {
self.elements = elements
}
/// Creates an SQLLiteral from a plain SQL string, and eventual arguments.
///
@@ -21,18 +92,37 @@ 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(elements: [.sql(sql, arguments)])
}
/// 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)])
}
// TODO: deprecate when SQL interpolation is always available
/// 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 {
return SQLLiteral(elements: [.map(self, transform)])
}
func sql(_ context: inout SQLGenerationContext) -> String {
return elements.map { $0.sql(&context) }.joined()
}
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.
///
@@ -52,8 +142,7 @@ 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.elements += rhs.elements
}
/// Appends an SQLLiteral to the receiver.
@@ -75,6 +164,25 @@ 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)
}
var sqlOrderingTerm: SQLOrderingTerm {
return SQLOrderingLiteral(sqlLiteral: self)
}
}
extension Sequence where Element == SQLLiteral {
/// Returns the concatenated SQLLiteral of this sequence of literals,
/// inserting the given separator between each element.
@@ -86,25 +194,17 @@ 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
if separator.isEmpty {
return SQLLiteral(elements: flatMap { $0.elements })
} else {
return SQLLiteral(elements: Array(map { $0.elements }.joined(separator: CollectionOfOne(.sql(separator)))))
}
return SQLLiteral(sql: sql, arguments: arguments)
}
}
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",
@@ -113,9 +213,11 @@ 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)
if separator.isEmpty {
return SQLLiteral(elements: flatMap { $0.elements })
} else {
return SQLLiteral(elements: Array(map { $0.elements }.joined(separator: CollectionOfOne(.sql(separator)))))
}
}
}
@@ -140,7 +242,142 @@ extension SQLLiteral: ExpressibleByStringInterpolation {
/// :nodoc:
public init(stringInterpolation sqlInterpolation: SQLInterpolation) {
self.init(sql: sqlInterpolation.sql, arguments: sqlInterpolation.arguments)
self.init(elements: sqlInterpolation.elements)
}
}
#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.sql(&context)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
return sqlLiteral.qualified(with: alias).sqlExpression
}
}
// 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.sql(&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 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
}
}
+7 -5
View File
@@ -31,7 +31,7 @@ public struct SQLRequest<T>: FetchRequest {
/// The request adapter
public var adapter: RowAdapter?
private var sqlLiteral: SQLLiteral
private(set) var sqlLiteral: SQLLiteral
private let cache: Cache?
/// Creates a request from an SQL string, optional arguments, and
@@ -146,16 +146,18 @@ public struct SQLRequest<T>: FetchRequest {
///
/// :nodoc:
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
var context = SQLGenerationContext.sqlLiteralContext
let sql = sqlLiteral.sql(&context)
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(context.arguments)
return PreparedRequest(statement: statement, adapter: adapter)
}
}
@@ -212,7 +212,7 @@ extension QueryInterfaceRequest: SelectionRequest {
as type: RowDecoder.Type = RowDecoder.self)
-> QueryInterfaceRequest<RowDecoder>
{
return select(SQLSelectionLiteral(literal: sqlLiteral), as: type)
return select(sqlLiteral.sqlSelectable, as: type)
}
/// Creates a request which appends *selection*.
@@ -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.sqlOrderingTerm)
}
}
@@ -6,86 +6,20 @@ extension SQLExpression {
/// Converts an expression to an SQLLiteral
///
/// :nodoc:
@available(*, deprecated, message: "Use SQLLiteral initializer 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(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)
}
}
// 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)))"
}
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
}
/// [**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)
@@ -23,50 +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 {
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
}
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)
@@ -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
}
@@ -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)
@@ -6,7 +6,7 @@ extension SQLInterpolation {
/// // SELECT * FROM player
/// let request: SQLRequest<Player> = "SELECT * FROM \(Player.self)"
public mutating func appendInterpolation<T: TableRecord>(_ 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<Player> = "INSERT INTO \(tableOf: player) ..."
public mutating func appendInterpolation<T: TableRecord>(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<T: SQLExpressible>(_ 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<T>(_ 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<S>(_ 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,7 @@ extension SQLInterpolation {
/// SELECT * FROM player WHERE score = \(subQuery)
/// """
public mutating func appendInterpolation<T>(_ request: SQLRequest<T>) {
sql += "(" + request.sql + ")"
arguments += request.arguments
elements.append(.subQuery(request.sqlLiteral))
}
}
#endif
@@ -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 {
@@ -904,7 +904,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
}
@@ -936,7 +936,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
}
+1 -1
View File
@@ -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: ", ")
-6
View File
@@ -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 = "<group>"; };
567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = "<group>"; };
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = "<group>"; };
567F0B2F220F196300D111FB /* SQLInterpolationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLInterpolationTests.swift; sourceTree = "<group>"; };
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
@@ -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 */,
@@ -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 = "<group>"; };
564A1F4D226B89D2001F64F1 /* AssociationChainSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainSQLTests.swift; sourceTree = "<group>"; };
564A1F4E226B89D2001F64F1 /* SQLExpressionLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpressionLiteralTests.swift; sourceTree = "<group>"; };
564A1F4F226B89D2001F64F1 /* SQLInterpolationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLInterpolationTests.swift; sourceTree = "<group>"; };
564A1F50226B89D2001F64F1 /* FoundationDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDataTests.swift; sourceTree = "<group>"; };
564A1F51226B89D2001F64F1 /* RecordInitializersTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordInitializersTests.swift; sourceTree = "<group>"; };
564A1F52226B89D2001F64F1 /* AssociationHasOneThroughSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLTests.swift; sourceTree = "<group>"; };
@@ -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 */,
@@ -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 = "<group>"; };
564A1F4D226B89D2001F64F1 /* AssociationChainSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainSQLTests.swift; sourceTree = "<group>"; };
564A1F4E226B89D2001F64F1 /* SQLExpressionLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpressionLiteralTests.swift; sourceTree = "<group>"; };
564A1F4F226B89D2001F64F1 /* SQLInterpolationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLInterpolationTests.swift; sourceTree = "<group>"; };
564A1F50226B89D2001F64F1 /* FoundationDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDataTests.swift; sourceTree = "<group>"; };
564A1F51226B89D2001F64F1 /* RecordInitializersTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordInitializersTests.swift; sourceTree = "<group>"; };
564A1F52226B89D2001F64F1 /* AssociationHasOneThroughSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLTests.swift; sourceTree = "<group>"; };
@@ -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 */,
+16 -20
View File
@@ -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\"")
}
}
}
@@ -37,7 +37,7 @@ func ~= (_ lhs: SQLExpressible, _ rhs: Column) -> SQLExpression {
// CAST
func cast(_ 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,6 +45,17 @@ func cast(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpressio
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)
private func castInterpolated<T: SQLExpressible>(_ value: T, as type: Database.ColumnType) -> SQLExpression {
return SQLLiteral("CAST(\(value) AS \(sql: type.rawValue))").sqlExpression
}
#endif
class QueryInterfaceExtensibilityTests: GRDBTestCase {
@@ -87,6 +98,37 @@ 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")
}
}
}
func testCast() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -117,4 +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
}
@@ -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))")
}
}
-210
View File
@@ -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<V: DatabaseValueConvertible>(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<Void>(sql: "SELECT * FROM player WHERE id = ?", arguments: [42]))
sql.appendInterpolation(SQLRequest<Void>(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
+83 -4
View File
@@ -108,6 +108,36 @@ 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)
}
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"
""")
}
}
}
}
#if swift(>=5.0)
@@ -255,16 +285,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 +426,54 @@ extension SQLLiteralTests {
""")
XCTAssertEqual(query.arguments, ["name": "Arthur"])
}
func testQualifiedSQLInterpolation() throws {
struct Player: TableRecord { }
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"))
do {
let alteredNameLiteral = SQLLiteral("\(nameColumn) || \("O'Brien")")
let request = baseRequest.select(literal: alteredNameLiteral)
try assertEqualSQL(db, request, """
SELECT "p"."name" || 'O''Brien' FROM "player" "p"
""")
}
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" || 'O''Brien' AS "alteredName" FROM "player" "p"
""")
}
do {
let subQuery: SQLRequest<String> = "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 {
// 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'
""")
}
}
}
}
#endif