forked from vapor/postgres-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathString+PostgresCodable.swift
49 lines (43 loc) · 1.37 KB
/
String+PostgresCodable.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
import NIOCore
import struct Foundation.UUID
extension String: PostgresEncodable {
public static var psqlType: PostgresDataType {
.text
}
public static var psqlFormat: PostgresFormat {
.binary
}
@inlinable
public func encode<JSONEncoder: PostgresJSONEncoder>(
into byteBuffer: inout ByteBuffer,
context: PostgresEncodingContext<JSONEncoder>
) {
byteBuffer.writeString(self)
}
}
extension String: PostgresDecodable {
@inlinable
public init<JSONDecoder: PostgresJSONDecoder>(
from buffer: inout ByteBuffer,
type: PostgresDataType,
format: PostgresFormat,
context: PostgresDecodingContext<JSONDecoder>
) throws {
switch (format, type) {
case (_, .varchar),
(_, .text),
(_, .name):
// we can force unwrap here, since this method only fails if there are not enough
// bytes available.
self = buffer.readString(length: buffer.readableBytes)!
case (_, .uuid):
guard let uuid = try? UUID(from: &buffer, type: .uuid, format: format, context: context) else {
throw PostgresDecodingError.Code.failure
}
self = uuid.uuidString
default:
throw PostgresDecodingError.Code.typeMismatch
}
}
}
extension String: PostgresCodable {}