forked from vapor/postgres-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgreSQLJSONType.swift
33 lines (28 loc) · 1.2 KB
/
PostgreSQLJSONType.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
import COperatingSystem
import Foundation
/// Representable by a `JSONB` column on the PostgreSQL database.
public protocol PostgreSQLJSONType: PostgreSQLDataCustomConvertible, Codable { }
extension PostgreSQLJSONType {
/// See `PostgreSQLDataCustomConvertible.preferredDataType`
public static var preferredDataType: PostgreSQLDataType? { return .jsonb }
/// See `PostgreSQLDataCustomConvertible.convertFromPostgreSQLData(_:)`
public static func convertFromPostgreSQLData(_ data: PostgreSQLData) throws -> Self {
guard let value = data.data else {
fatalError()
}
switch data.type {
case .jsonb:
switch data.format {
case .text: return try JSONDecoder().decode(Self.self, from: value)
case .binary:
assert(value[0] == 0x01)
return try JSONDecoder().decode(Self.self, from: value[1...])
}
default: fatalError()
}
}
/// See `PostgreSQLDataCustomConvertible.convertToPostgreSQLData()`
public func convertToPostgreSQLData() throws -> PostgreSQLData {
return try PostgreSQLData(type: .jsonb, format: .text, data: JSONEncoder().encode(self))
}
}