Skip to content

Instantly share code, notes, and snippets.

@davbeck
Last active July 27, 2018 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davbeck/a3f96cf2f2df166ec8679c0e0737f4cb to your computer and use it in GitHub Desktop.
Save davbeck/a3f96cf2f2df166ec8679c0e0737f4cb to your computer and use it in GitHub Desktop.
// 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);"
// 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