SQLRequest adopts ExpressibleByStringInterpolation

This commit is contained in:
Gwendal Roué committed 2019-02-17 13:24:37 +01:00
1 parent 87ee00c2c5
commit 5b6d882d67
3 files changed
+109

No files matched your search

+3
View File
@@ -51,6 +51,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection:
- Deprecated APIs are no longer available.
- `SQLRequest.arguments` is no longer optional
### New
- SQL interpolation (SQLRequest)
## 3.6.2
+22
View File
@@ -246,3 +246,25 @@ public struct SQLRequest<T> : FetchRequest {
case `internal`
}
}
extension SQLRequest: ExpressibleByStringInterpolation {
/// :nodoc
public init(unicodeScalarLiteral: String) {
self.init(unicodeScalarLiteral)
}
/// :nodoc:
public init(extendedGraphemeClusterLiteral: String) {
self.init(extendedGraphemeClusterLiteral)
}
/// :nodoc:
public init(stringLiteral: String) {
self.init(stringLiteral)
}
/// :nodoc:
public init(stringInterpolation sqlInterpolation: SQLInterpolation) {
self.init(sqlInterpolation.sql, arguments: sqlInterpolation.arguments)
}
}
+84
View File
@@ -71,4 +71,88 @@ class SQLRequestTests: GRDBTestCase {
XCTAssertEqual(try sqlRequest.fetchOne(db)!, ["a": 1, "b": "foo"])
}
}
func testSQLInterpolation() throws {
struct Player: Codable, TableRecord {
var id: Int64?
var name: String
static func filter(id: Int64) -> SQLRequest<Player> {
return """
SELECT *
FROM \(self)
WHERE \(CodingKeys.id) = \(id)
"""
}
static func filter(ids: [Int64]) -> SQLRequest<Player> {
return """
SELECT *
FROM \(self)
WHERE \(CodingKeys.id) IN \(ids)
"""
}
static func genericFilter<S>(ids: S) -> SQLRequest<Player> where S: Sequence, S.Element == Int64 {
return """
SELECT *
FROM \(self)
WHERE \(CodingKeys.id) IN \(ids)
"""
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
}
do {
let request = Player.filter(id: 42)
XCTAssertEqual(request.sql, """
SELECT *
FROM "player"
WHERE "id" = ?
""")
_ = try Row.fetchOne(db, request)
XCTAssertEqual(lastSQLQuery, """
SELECT *
FROM "player"
WHERE "id" = 42
""")
}
do {
let request = Player.filter(ids: [1, 2, 3])
XCTAssertEqual(request.sql, """
SELECT *
FROM "player"
WHERE "id" IN (?,?,?)
""")
_ = try Row.fetchOne(db, request)
XCTAssertEqual(lastSQLQuery, """
SELECT *
FROM "player"
WHERE "id" IN (1,2,3)
""")
}
do {
let request = Player.genericFilter(ids: [42, 666])
XCTAssertEqual(request.sql, """
SELECT *
FROM "player"
WHERE "id" IN (?,?)
""")
_ = try Row.fetchOne(db, request)
XCTAssertEqual(lastSQLQuery, """
SELECT *
FROM "player"
WHERE "id" IN (42,666)
""")
}
}
}
}