forked from vapor/postgres-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgresData+String.swift
110 lines (103 loc) · 3.43 KB
/
PostgresData+String.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
extension PostgresData {
public init(string: String) {
var buffer = ByteBufferAllocator().buffer(capacity: string.utf8.count)
buffer.writeString(string)
self.init(type: .text, formatCode: .binary, value: buffer)
}
public var string: String? {
guard var value = self.value else {
return nil
}
switch self.formatCode {
case .binary:
switch self.type {
case .varchar, .text, .name:
guard let string = value.readString(length: value.readableBytes) else {
return nil
}
return string
case .numeric:
return self.numeric?.string
case .uuid:
return value.readUUID()!.uuidString
case .timestamp, .timestamptz, .date:
return self.date?.description
case .money:
assert(value.readableBytes == 8)
guard let int64 = value.getInteger(at: value.readerIndex, as: Int64.self) else {
return nil
}
let description = int64.description
switch description.count {
case 0:
return "0.00"
case 1:
return "0.0" + description
case 2:
return "0." + description
default:
let decimalIndex = description.index(description.endIndex, offsetBy: -2)
return description[description.startIndex..<decimalIndex]
+ "."
+ description[decimalIndex..<description.endIndex]
}
case .float4, .float8:
return self.double?.description
case .int2, .int4, .int8:
return self.int?.description
case .bpchar:
return value.readString(length: value.readableBytes)
default:
if self.type.isUserDefined {
// custom type
return value.readString(length: value.readableBytes)
} else {
return nil
}
}
case .text:
guard let string = value.readString(length: value.readableBytes) else {
return nil
}
return string
}
}
public var character: Character? {
guard var value = self.value else {
return nil
}
switch self.formatCode {
case .binary:
switch self.type {
case .bpchar:
guard let byte = value.readInteger(as: UInt8.self) else {
return nil
}
return Character(UnicodeScalar(byte))
default:
return nil
}
case .text:
return nil
}
}
}
extension PostgresData: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.init(string: value)
}
}
extension String: PostgresDataConvertible {
public static var postgresDataType: PostgresDataType {
return .text
}
public var postgresData: PostgresData? {
return .init(string: self)
}
public init?(postgresData: PostgresData) {
guard let string = postgresData.string else {
return nil
}
self = string
}
}