forked from vapor/postgres-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDate+PostgresCodable.swift
59 lines (52 loc) · 1.99 KB
/
Date+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
50
51
52
53
54
55
56
57
58
59
import NIOCore
import struct Foundation.Date
extension Date: PostgresNonThrowingEncodable {
public static var psqlType: PostgresDataType {
.timestamptz
}
public static var psqlFormat: PostgresFormat {
.binary
}
@inlinable
public func encode<JSONEncoder: PostgresJSONEncoder>(
into byteBuffer: inout ByteBuffer,
context: PostgresEncodingContext<JSONEncoder>
) {
let seconds = self.timeIntervalSince(Self._psqlDateStart) * Double(Self._microsecondsPerSecond)
byteBuffer.writeInteger(Int64(seconds))
}
// MARK: Private Constants
@usableFromInline
static let _microsecondsPerSecond: Int64 = 1_000_000
@usableFromInline
static let _secondsInDay: Int64 = 24 * 60 * 60
/// values are stored as seconds before or after midnight 2000-01-01
@usableFromInline
static let _psqlDateStart = Date(timeIntervalSince1970: 946_684_800)
}
extension Date: PostgresDecodable {
@inlinable
public init<JSONDecoder: PostgresJSONDecoder>(
from buffer: inout ByteBuffer,
type: PostgresDataType,
format: PostgresFormat,
context: PostgresDecodingContext<JSONDecoder>
) throws {
switch type {
case .timestamp, .timestamptz:
guard buffer.readableBytes == 8, let microseconds = buffer.readInteger(as: Int64.self) else {
throw PostgresDecodingError.Code.failure
}
let seconds = Double(microseconds) / Double(Self._microsecondsPerSecond)
self = Date(timeInterval: seconds, since: Self._psqlDateStart)
case .date:
guard buffer.readableBytes == 4, let days = buffer.readInteger(as: Int32.self) else {
throw PostgresDecodingError.Code.failure
}
let seconds = Int64(days) * Self._secondsInDay
self = Date(timeInterval: Double(seconds), since: Self._psqlDateStart)
default:
throw PostgresDecodingError.Code.typeMismatch
}
}
}