Last active
July 27, 2018 16:05
-
-
Save davbeck/a3f96cf2f2df166ec8679c0e0737f4cb to your computer and use it in GitHub Desktop.
PG.swift example of https://gist.github.com/brentdax/fe23d4d9b0fdf8cd1949094f6ef1a936
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// original: | |
Query("SELECT * FROM example WHERE e_uuid = $1;", idA) | |
// or | |
Query("SELECT * FROM example WHERE e_uuid = $1;", [idA]) | |
// manual interpolation test: | |
var query = Query(stringInterpolation: { | |
var temp = Query.StringInterpolation(totalLiteralSize: 40, interpolationCount: 1) | |
temp.appendLiteral("SELECT * FROM example WHERE e_uuid = ") | |
temp.appendInterpolation(idA) | |
temp.appendLiteral(";") | |
return temp | |
}()) | |
// proposed compiler feature: | |
var query: Query = "SELECT * FROM example WHERE e_uuid = \(idA);" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// note Query already impliments ExpressibleByStringLiteral | |
public protocol ExpressibleByStringInterpolation: ExpressibleByStringLiteral { | |
associatedtype StringInterpolation: StringInterpolationProtocol | |
where StringInterpolation.StringLiteralType == StringLiteralType | |
init(stringInterpolation: StringInterpolation) | |
} | |
public protocol StringInterpolationProtocol { | |
associatedtype StringLiteralType : _ExpressibleByBuiltinStringLiteral | |
init(totalLiteralSize literalCodeUnits: Int, interpolationCount: Int) | |
mutating func appendLiteral(_ literal: StringLiteralType) | |
mutating func appendInterpolation(_ binding: PostgresCodable?) | |
} | |
extension Query: ExpressibleByStringInterpolation { | |
public typealias StringInterpolation = _StringInterpolation | |
public struct _StringInterpolation: StringInterpolationProtocol { | |
public typealias StringInterpolation = String | |
var string: String = "" | |
var bindings: [PostgresCodable?] = [] | |
public init(totalLiteralSize literalCodeUnits: Int, interpolationCount: Int) { | |
self.string.reserveCapacity(literalCodeUnits) | |
self.bindings.reserveCapacity(interpolationCount) | |
} | |
public mutating func appendLiteral(_ literal: String) { | |
string.append(literal) | |
} | |
public mutating func appendInterpolation(_ binding: PostgresCodable?) { | |
bindings.append(binding) | |
// intentionally starting with $1 | |
string.append("$\(bindings.count)") | |
} | |
} | |
public init(stringInterpolation: StringInterpolation) { | |
self.init(stringInterpolation.string, bindings: stringInterpolation.bindings) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment