postgres-nio icon indicating copy to clipboard operation
postgres-nio copied to clipboard

Document how to conform your own type to `PostgresEncodable` and `PostgresDecodable`

Open fabianfett opened this issue 2 years ago • 0 comments

Document how to conform your own type to PostgresEncodable and PostgresDecodable.

  1. As an example we can use a custom MyPoint type that shall be transformed to the Postgres type.
  2. 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)
    }
}

fabianfett avatar Apr 25 '22 20:04 fabianfett