postgres-nio
postgres-nio copied to clipboard
Document how to conform your own type to `PostgresEncodable` and `PostgresDecodable`
Document how to conform your own type to PostgresEncodable
and PostgresDecodable
.
- As an example we can use a custom
MyPoint
type that shall be transformed to the Postgres type. - Write down how developers can reverse engineer postgres types from the wire format.
Context: https://forums.swift.org/t/how-to-create-a-postgresdata-for-one-of-postgres-point-types/56939
struct MyPoint { // Remove conformance to PostgresDataConvertible
var x: Double
var y: Double
}
extension MyPoint: PostgresEncodable {
static var psqlFormat: PostgresFormat {
.binary
}
static var psqlType: PostgresDataType {
.point
}
func encode<JSONEncoder>(into byteBuffer: inout ByteBuffer, context: PostgresEncodingContext<JSONEncoder>) throws where JSONEncoder : PostgresJSONEncoder {
byteBuffer.writeMultipleIntegers(self.x.bitPattern, self.y.bitPattern)
}
}
extension MyPoint: PostgresDecodable {
init<JSONDecoder>(from byteBuffer: inout ByteBuffer, type: PostgresDataType, format: PostgresFormat, context: PostgresDecodingContext<JSONDecoder>) throws where JSONDecoder : PostgresJSONDecoder {
guard type == .point, let (x, y) = byteBuffer.readMultipleIntegers(as: (UInt64, UInt64).self) else {
throw MyError()
}
self.x = Double(bitPattern: x)
self.y = Double(bitPattern: y)
}
}