From 77144083b43cba5f9efaf328c5481e008b507c88 Mon Sep 17 00:00:00 2001 From: Ben Syverson Date: Tue, 20 Feb 2018 22:03:40 -0600 Subject: [PATCH] Adds conformance to RawRepresentable to ease enum encoding --- .../PostgreSQLDataCustomConvertible.swift | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/Sources/PostgreSQL/Data/PostgreSQLDataCustomConvertible.swift b/Sources/PostgreSQL/Data/PostgreSQLDataCustomConvertible.swift index bd96d0fe..11162ef9 100644 --- a/Sources/PostgreSQL/Data/PostgreSQLDataCustomConvertible.swift +++ b/Sources/PostgreSQL/Data/PostgreSQLDataCustomConvertible.swift @@ -37,3 +37,25 @@ extension PostgreSQLData: PostgreSQLDataCustomConvertible { return self } } + +extension RawRepresentable where RawValue: PostgreSQLDataCustomConvertible { + static var postgreSQLDataType: PostgreSQLDataType { + return Self.postgreSQLDataType + } + + static var postgreSQLDataArrayType: PostgreSQLDataType { + return Self.postgreSQLDataArrayType + } + + static func convertFromPostgreSQLData(_ data: PostgreSQLData) throws -> Self { + let aRawValue = try RawValue.convertFromPostgreSQLData(data) + guard let enumValue = Self(rawValue: aRawValue) else { + throw PostgreSQLError(identifier: "invalidRawValue", reason: "Unable to decode RawRepresentable from the database value.") + } + return enumValue + } + + func convertToPostgreSQLData() throws -> PostgreSQLData { + return try self.rawValue.convertToPostgreSQLData() + } +}