forked from vapor/postgres-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgreSQLDataConvertible.swift
65 lines (53 loc) · 2.63 KB
/
PostgreSQLDataConvertible.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/// Capable of being converted to/from `PostgreSQLData`
public protocol PostgreSQLDataConvertible {
/// This type's preferred data type.
static var postgreSQLDataType: PostgreSQLDataType { get }
/// This type's preferred array type.
static var postgreSQLDataArrayType: PostgreSQLDataType { get }
/// Creates a `Self` from the supplied `PostgreSQLData`
static func convertFromPostgreSQLData(_ data: PostgreSQLData) throws -> Self
/// Converts `Self` to a `PostgreSQLData`
func convertToPostgreSQLData() throws -> PostgreSQLData
}
extension PostgreSQLData {
/// Gets a `String` from the supplied path or throws a decoding error.
public func decode<T>(_ type: T.Type) throws -> T where T: PostgreSQLDataConvertible {
return try T.convertFromPostgreSQLData(self)
}
}
extension PostgreSQLData: PostgreSQLDataConvertible {
/// See `PostgreSQLDataCustomConvertible.postgreSQLDataType`
public static var postgreSQLDataType: PostgreSQLDataType { return .void }
/// See `PostgreSQLDataCustomConvertible.postgreSQLDataArrayType`
public static var postgreSQLDataArrayType: PostgreSQLDataType { return .void }
/// See `PostgreSQLDataCustomConvertible.convertFromPostgreSQLData(_:)`
public static func convertFromPostgreSQLData(_ data: PostgreSQLData) throws -> PostgreSQLData {
return data
}
/// See `PostgreSQLDataCustomConvertible.convertToPostgreSQLData()`
public func convertToPostgreSQLData() throws -> PostgreSQLData {
return self
}
}
extension RawRepresentable where RawValue: PostgreSQLDataConvertible {
/// See `PostgreSQLDataCustomConvertible.postgreSQLDataType`
public static var postgreSQLDataType: PostgreSQLDataType {
return RawValue.postgreSQLDataType
}
/// See `PostgreSQLDataCustomConvertible.postgreSQLDataArrayType`
public static var postgreSQLDataArrayType: PostgreSQLDataType {
return RawValue.postgreSQLDataArrayType
}
/// See `PostgreSQLDataCustomConvertible.convertFromPostgreSQLData(_:)`
public 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.", source: .capture())
}
return enumValue
}
/// See `PostgreSQLDataCustomConvertible.convertToPostgreSQLData()`
public func convertToPostgreSQLData() throws -> PostgreSQLData {
return try self.rawValue.convertToPostgreSQLData()
}
}