forked from vapor/postgres-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgreSQLData+UUID.swift
34 lines (31 loc) · 1.46 KB
/
PostgreSQLData+UUID.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
import Foundation
extension UUID: PostgreSQLDataCustomConvertible {
/// See `PostgreSQLDataCustomConvertible.preferredDataType`
public static var preferredDataType: PostgreSQLDataType? { return .uuid }
/// See `PostgreSQLDataCustomConvertible.convertFromPostgreSQLData(_:)`
public static func convertFromPostgreSQLData(_ data: PostgreSQLData) throws -> UUID {
guard let value = data.data else {
throw PostgreSQLError(identifier: "data", reason: "Could not decode UUID from `null` data.")
}
switch data.type {
case .uuid:
switch data.format {
case .text:
let string = try value.makeString()
guard let uuid = UUID(uuidString: string) else {
throw PostgreSQLError(identifier: "uuid", reason: "Could not decode UUID from string: \(string)")
}
return uuid
case .binary: return UUID(uuid: value.unsafeCast())
}
default: throw PostgreSQLError(identifier: "uuid", reason: "Could not decode UUID from data type: \(data.type)")
}
}
/// See `PostgreSQLDataCustomConvertible.convertToPostgreSQLData()`
public func convertToPostgreSQLData() throws -> PostgreSQLData {
var uuid = self.uuid
return PostgreSQLData(type: .uuid, format: .binary, data: withUnsafePointer(to: &uuid) {
Data(bytes: $0, count: MemoryLayout.size(ofValue: uuid))
})
}
}