|
| 1 | +import Foundation |
| 2 | + |
| 3 | +extension Date: PostgreSQLDataCustomConvertible { |
| 4 | + /// See `PostgreSQLDataCustomConvertible.preferredDataType` |
| 5 | + public static var preferredDataType: PostgreSQLDataType? { return .timestamp } |
| 6 | + |
| 7 | + /// See `PostgreSQLDataCustomConvertible.convertFromPostgreSQLData(_:)` |
| 8 | + public static func convertFromPostgreSQLData(_ data: PostgreSQLData) throws -> Date { |
| 9 | + guard let value = data.data else { |
| 10 | + throw PostgreSQLError(identifier: "data", reason: "Could not decode String from `null` data.") |
| 11 | + } |
| 12 | + switch data.format { |
| 13 | + case .text: |
| 14 | + switch data.type { |
| 15 | + case .timestamp: return try value.makeString().parseDate(format: "yyyy-MM-dd HH:mm:ss") |
| 16 | + case .date: return try value.makeString().parseDate(format: "yyyy-MM-dd") |
| 17 | + case .time: return try value.makeString().parseDate(format: "HH:mm:ss") |
| 18 | + default: throw PostgreSQLError(identifier: "date", reason: "Could not parse Date from text data type: \(data.type).") |
| 19 | + } |
| 20 | + case .binary: throw PostgreSQLError(identifier: "date", reason: "Could not parse Date from binary data type: \(data.type).") |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + /// See `PostgreSQLDataCustomConvertible.convertToPostgreSQLData()` |
| 25 | + public func convertToPostgreSQLData() throws -> PostgreSQLData { |
| 26 | + return PostgreSQLData(type: .timestamp, format: .text, data: Data(description.utf8)) |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +extension String { |
| 31 | + /// Parses a Date from this string with the supplied date format. |
| 32 | + fileprivate func parseDate(format: String) throws -> Date { |
| 33 | + let formatter = DateFormatter() |
| 34 | + if contains(".") { |
| 35 | + formatter.dateFormat = format + ".SSSSSS" |
| 36 | + } else { |
| 37 | + formatter.dateFormat = format |
| 38 | + } |
| 39 | + formatter.timeZone = TimeZone(secondsFromGMT: 0) |
| 40 | + guard let date = formatter.date(from: self) else { |
| 41 | + throw PostgreSQLError(identifier: "date", reason: "Malformed date: \(self)") |
| 42 | + } |
| 43 | + return date |
| 44 | + } |
| 45 | +} |
0 commit comments