Files
GRDB.swift/Tests/Public/Core/DatabaseValueConvertible/DatabaseTimestampTests.swift
T
Gwendal Roué f44ae2848f Project organization
Project organization

README.md

WIP QueryBuilder documentation

README.md

WIP QueryBuilder documentation

WIP QueryBuilder documentation

TODO.md
2016-01-28 08:43:25 +01:00

60 lines
1.9 KiB
Swift

import XCTest
import GRDB
struct DatabaseTimestamp: DatabaseValueConvertible {
// NSDate conversion
//
// We consistently use the Swift nil to represent the database NULL: the
// date property is a non-optional NSDate, and the NSDate initializer is
// failable:
/// The represented date
let date: NSDate
/// Creates a DatabaseTimestamp from an NSDate.
/// The result is nil if and only if *date* is nil.
init?(_ date: NSDate?) {
guard let date = date else {
return nil
}
self.date = date
}
// DatabaseValueConvertible adoption
/// Returns a value that can be stored in the database.
var databaseValue: DatabaseValue {
return date.timeIntervalSince1970.databaseValue
}
/// Returns a value initialized from *databaseValue*, if possible.
static func fromDatabaseValue(databaseValue: DatabaseValue) -> DatabaseTimestamp? {
// Double itself adopts DatabaseValueConvertible. So let's avoid
// handling the raw DatabaseValue, and use built-in Double conversion:
guard let timeInterval = Double.fromDatabaseValue(databaseValue) else {
// No Double, no NSDate!
return nil
}
return DatabaseTimestamp(NSDate(timeIntervalSince1970: timeInterval))
}
}
class DatabaseTimestampTests: GRDBTestCase {
func testDatabaseTimestamp() {
assertNoError {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE dates (date DATETIME)")
let storedDate = NSDate()
try db.execute("INSERT INTO dates (date) VALUES (?)", arguments: [DatabaseTimestamp(storedDate)])
let fetchedDate = DatabaseTimestamp.fetchOne(db, "SELECT date FROM dates")!.date
let delta = storedDate.timeIntervalSinceDate(fetchedDate)
XCTAssertTrue(abs(delta) < 0.1)
}
}
}
}