Public support for NSDate through DateTime

This commit is contained in:
Gwendal Roué committed 2015-07-21 15:06:56 +02:00
1 parent ca9c2f64de
commit 98dc15ff51
8 files changed
+110 -75

No files matched your search

-49
View File
@@ -25,55 +25,6 @@
import XCTest
import GRDB
struct DBDate: DatabaseValueConvertible {
// NSDate conversion
//
// It is good to 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 DBDate from an NSDate.
// Returns nil if and only if the NSDate is nil.
init?(_ date: NSDate?) {
if let date = date {
self.date = date
} else {
return nil
}
}
// DatabaseValue conversion
//
// DBDate represents the date as an ISO-8601 string in the database.
// An ISO-8601 date formatter
static let dateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
return formatter
}()
var databaseValue: DatabaseValue {
return .Text(DBDate.dateFormatter.stringFromDate(date))
}
init?(databaseValue: DatabaseValue) {
// Don't handle the raw DatabaseValue unless you know what you do.
// It is recommended to use GRDB built-in conversions instead:
if let string = String(databaseValue: databaseValue) {
self.init(DBDate.dateFormatter.dateFromString(string))
} else {
return nil
}
}
}
class GRDBTestCase: XCTestCase {
var databasePath: String!
var dbQueue: DatabaseQueue!
@@ -25,7 +25,7 @@
import XCTest
import GRDB
class DBDateTests : GRDBTestCase {
class DateTimeTests : GRDBTestCase {
override func setUp() {
super.setUp()
@@ -43,7 +43,7 @@ class DBDateTests : GRDBTestCase {
}
}
func testDBDate() {
func testDateTime() {
assertNoError {
try dbQueue.inTransaction { db in
@@ -59,12 +59,12 @@ class DBDateTests : GRDBTestCase {
do {
let date = calendar.dateFromComponents(dateComponents)!
try db.execute("INSERT INTO stuffs (creationDate) VALUES (?)", arguments: [DBDate(date)])
try db.execute("INSERT INTO stuffs (creationDate) VALUES (?)", arguments: [DateTime(date)])
}
do {
let row = db.fetchOneRow("SELECT creationDate FROM stuffs")!
let date = (row.value(atIndex: 0)! as DBDate).date
let date = (row.value(atIndex: 0)! as DateTime).date
// All components must be preserved, but nanosecond since ISO-8601 stores milliseconds.
XCTAssertEqual(calendar.component(NSCalendarUnit.Year, fromDate: date), dateComponents.year)
XCTAssertEqual(calendar.component(NSCalendarUnit.Month, fromDate: date), dateComponents.month)
@@ -76,7 +76,7 @@ class DBDateTests : GRDBTestCase {
}
do {
let date = db.fetchOne(DBDate.self, "SELECT creationDate FROM stuffs")!.date
let date = db.fetchOne(DateTime.self, "SELECT creationDate FROM stuffs")!.date
// All components must be preserved, but nanosecond since ISO-8601 stores milliseconds.
XCTAssertEqual(calendar.component(NSCalendarUnit.Year, fromDate: date), dateComponents.year)
XCTAssertEqual(calendar.component(NSCalendarUnit.Month, fromDate: date), dateComponents.month)
@@ -41,7 +41,7 @@ class Person: RowModel {
"id": id,
"name": name,
"age": age,
"creationDate": DBDate(creationDate),
"creationDate": DateTime(creationDate),
]
}
@@ -50,7 +50,7 @@ class Person: RowModel {
case "id": id = dbv.value()
case "name": name = dbv.value()
case "age": age = dbv.value()
case "creationDate": creationDate = (dbv.value() as DBDate?)?.date
case "creationDate": creationDate = (dbv.value() as DateTime?)?.date
default: super.setDatabaseValue(dbv, forColumn: column)
}
}
+12 -6
View File
@@ -7,6 +7,8 @@
objects = {
/* Begin PBXBuildFile section */
5645E69D1B5E76D30045DC8F /* DateTime.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5645E69C1B5E76D30045DC8F /* DateTime.swift */; };
5645E69E1B5E76D30045DC8F /* DateTime.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5645E69C1B5E76D30045DC8F /* DateTime.swift */; };
564E0B141B4D8FC100EBC9F6 /* DatabaseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E0B131B4D8FC100EBC9F6 /* DatabaseError.swift */; };
564E0B161B4D901300EBC9F6 /* DatabaseValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E0B151B4D901300EBC9F6 /* DatabaseValue.swift */; };
565E191E1B42B2B600D32814 /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565E191D1B42B2B600D32814 /* Database.swift */; };
@@ -21,8 +23,8 @@
56997A3A1B539038005EBEED /* DatabaseErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5699796A1B539038005EBEED /* DatabaseErrorTests.swift */; };
56997A3B1B539038005EBEED /* DatabaseMigratorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5699796C1B539038005EBEED /* DatabaseMigratorTests.swift */; };
56997A3C1B539038005EBEED /* DatabaseMigratorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5699796C1B539038005EBEED /* DatabaseMigratorTests.swift */; };
56997A3D1B539038005EBEED /* DBDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5699796E1B539038005EBEED /* DBDateTests.swift */; };
56997A3E1B539038005EBEED /* DBDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5699796E1B539038005EBEED /* DBDateTests.swift */; };
56997A3D1B539038005EBEED /* DateTimeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5699796E1B539038005EBEED /* DateTimeTests.swift */; };
56997A3E1B539038005EBEED /* DateTimeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5699796E1B539038005EBEED /* DateTimeTests.swift */; };
56997A3F1B539038005EBEED /* DatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5699796F1B539038005EBEED /* DatabaseValueConvertibleTests.swift */; };
56997A401B539038005EBEED /* DatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5699796F1B539038005EBEED /* DatabaseValueConvertibleTests.swift */; };
56997A411B539038005EBEED /* RawRepresentableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569979701B539038005EBEED /* RawRepresentableTests.swift */; };
@@ -116,6 +118,7 @@
/* Begin PBXFileReference section */
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = "<group>"; };
5645E69C1B5E76D30045DC8F /* DateTime.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DateTime.swift; sourceTree = "<group>"; };
564E0B131B4D8FC100EBC9F6 /* DatabaseError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseError.swift; sourceTree = "<group>"; };
564E0B151B4D901300EBC9F6 /* DatabaseValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValue.swift; sourceTree = "<group>"; };
565E191D1B42B2B600D32814 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = "<group>"; };
@@ -125,7 +128,7 @@
569979681B539038005EBEED /* InMemoryDatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InMemoryDatabaseTests.swift; sourceTree = "<group>"; };
5699796A1B539038005EBEED /* DatabaseErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseErrorTests.swift; sourceTree = "<group>"; };
5699796C1B539038005EBEED /* DatabaseMigratorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseMigratorTests.swift; sourceTree = "<group>"; };
5699796E1B539038005EBEED /* DBDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DBDateTests.swift; sourceTree = "<group>"; };
5699796E1B539038005EBEED /* DateTimeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DateTimeTests.swift; sourceTree = "<group>"; };
5699796F1B539038005EBEED /* DatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleTests.swift; sourceTree = "<group>"; };
569979701B539038005EBEED /* RawRepresentableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RawRepresentableTests.swift; sourceTree = "<group>"; };
569979731B539038005EBEED /* FetchedRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRowTests.swift; sourceTree = "<group>"; };
@@ -259,7 +262,7 @@
isa = PBXGroup;
children = (
5699796F1B539038005EBEED /* DatabaseValueConvertibleTests.swift */,
5699796E1B539038005EBEED /* DBDateTests.swift */,
5699796E1B539038005EBEED /* DateTimeTests.swift */,
569979701B539038005EBEED /* RawRepresentableTests.swift */,
);
path = DatabaseValueConvertible;
@@ -390,6 +393,7 @@
56CC3C8E1B43A5A700A9A534 /* DatabaseQueue.swift */,
564E0B151B4D901300EBC9F6 /* DatabaseValue.swift */,
5699AE5E1B42E59F00C35172 /* DatabaseValueConvertible.swift */,
5645E69C1B5E76D30045DC8F /* DateTime.swift */,
56E4BB801B45373600FD324B /* QueryArguments.swift */,
5699AE581B42CD7800C35172 /* Row.swift */,
56CC3C9A1B4464AE00A9A534 /* RowModel.swift */,
@@ -599,6 +603,7 @@
56E5D8311B4D43FA00430942 /* DatabaseMigrator.swift in Sources */,
56B8F4491B4E1C7800C24296 /* DatabaseError.swift in Sources */,
56E5D8351B4D43FA00430942 /* SelectStatement.swift in Sources */,
5645E69E1B5E76D30045DC8F /* DateTime.swift in Sources */,
56E5D8371B4D43FA00430942 /* DatabaseValueConvertible.swift in Sources */,
56E5D8391B4D43FA00430942 /* UpdateStatement.swift in Sources */,
56B8F44A1B4E1C8600C24296 /* DatabaseValue.swift in Sources */,
@@ -634,7 +639,7 @@
56997A461B539038005EBEED /* FetchedRowTests.swift in Sources */,
56E5D8181B4D435D00430942 /* GRDBTestCase.swift in Sources */,
56997A641B539038005EBEED /* UpdateStatementTests.swift in Sources */,
56997A3E1B539038005EBEED /* DBDateTests.swift in Sources */,
56997A3E1B539038005EBEED /* DateTimeTests.swift in Sources */,
56997A501B539038005EBEED /* PrimaryKeyRowIDTests.swift in Sources */,
56997A3C1B539038005EBEED /* DatabaseMigratorTests.swift in Sources */,
56997A621B539038005EBEED /* SelectStatementTests.swift in Sources */,
@@ -668,7 +673,7 @@
56997A451B539038005EBEED /* FetchedRowTests.swift in Sources */,
56E5D8041B4D424400430942 /* GRDBTestCase.swift in Sources */,
56997A631B539038005EBEED /* UpdateStatementTests.swift in Sources */,
56997A3D1B539038005EBEED /* DBDateTests.swift in Sources */,
56997A3D1B539038005EBEED /* DateTimeTests.swift in Sources */,
56997A4F1B539038005EBEED /* PrimaryKeyRowIDTests.swift in Sources */,
56997A3B1B539038005EBEED /* DatabaseMigratorTests.swift in Sources */,
56997A611B539038005EBEED /* SelectStatementTests.swift in Sources */,
@@ -687,6 +692,7 @@
56CC3C931B43BF0100A9A534 /* Configuration.swift in Sources */,
564E0B161B4D901300EBC9F6 /* DatabaseValue.swift in Sources */,
56CC3C951B43C0E600A9A534 /* DatabaseMigrator.swift in Sources */,
5645E69D1B5E76D30045DC8F /* DateTime.swift in Sources */,
5699AE5D1B42D49C00C35172 /* UpdateStatement.swift in Sources */,
565E191E1B42B2B600D32814 /* Database.swift in Sources */,
5699AE5B1B42D3DC00C35172 /* SelectStatement.swift in Sources */,
+74
View File
@@ -0,0 +1,74 @@
//
// GRDB.swift
// https://github.com/groue/GRDB.swift
// Copyright (c) 2015 Gwendal Roué
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
public struct DateTime: DatabaseValueConvertible {
// MARK: - 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
public let date: NSDate
/// Creates a DateTime from an NSDate.
/// Returns nil if and only if the NSDate is nil.
public init?(_ date: NSDate?) {
if let date = date {
self.date = date
} else {
return nil
}
}
// MARK: - DatabaseValue conversion
//
// DateTime represents an NSDate as an ISO-8601 string.
// An ISO-8601 date formatter
static let dateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
return formatter
}()
public var databaseValue: DatabaseValue {
return .Text(DateTime.dateFormatter.stringFromDate(date))
}
public init?(databaseValue: DatabaseValue) {
// Don't handle the raw DatabaseValue since GRDB built-in conversions
// do all the job for us:
if let string = String(databaseValue: databaseValue) {
self.init(DateTime.dateFormatter.dateFromString(string))
} else {
return nil
}
}
}
+12 -12
View File
@@ -358,10 +358,10 @@ All types that adopt this protocol can be used wherever the built-in types `Int`
> Unfortunately not all types can adopt this protocol: **Swift won't allow non-final classes to adopt DatabaseValueConvertible, and this prevents all our NSObject fellows to enter the game.**
As an example, let's define the `DBDate` type that stores NSDates as ISO-8601 strings (a format understood by [SQLite date & time functions](https://www.sqlite.org/lang_datefunc.html)). DBDate applies all the best practices for a great GRDB.swift integration:
As an example, let's look at the implementation of the `GRDB.DateTime` type that stores NSDates as ISO-8601 strings. DateTime applies all the best practices for a great GRDB.swift integration:
```swift
struct DBDate: DatabaseValueConvertible {
struct DateTime: DatabaseValueConvertible {
// NSDate conversion
//
@@ -372,7 +372,7 @@ struct DBDate: DatabaseValueConvertible {
// The represented date
let date: NSDate
// Creates a DBDate from an NSDate.
// Creates a DateTime from an NSDate.
// Returns nil if and only if the NSDate is nil.
init?(_ date: NSDate?) {
if let date = date {
@@ -384,7 +384,7 @@ struct DBDate: DatabaseValueConvertible {
// DatabaseValue conversion
//
// DBDate represents the date as an ISO-8601 string in the database.
// DateTime represents the date as an ISO-8601 string in the database.
// An ISO-8601 date formatter
static let dateFormatter: NSDateFormatter = {
@@ -396,14 +396,14 @@ struct DBDate: DatabaseValueConvertible {
}()
var databaseValue: DatabaseValue {
return .Text(DBDate.dateFormatter.stringFromDate(date))
return .Text(DateTime.dateFormatter.stringFromDate(date))
}
init?(databaseValue: DatabaseValue) {
// Don't handle the raw DatabaseValue unless you know what you do.
// It is recommended to use GRDB built-in conversions instead:
if let string = String(databaseValue: databaseValue) {
self.init(DBDate.dateFormatter.dateFromString(string))
self.init(DateTime.dateFormatter.dateFromString(string))
} else {
return nil
}
@@ -411,24 +411,24 @@ struct DBDate: DatabaseValueConvertible {
}
```
DBDate can now be stored and fetched from the database just like built-in types:
As a DatabaseValueConvertible adopter, DateTime can be stored and fetched from the database just like simple types Int and String:
```swift
// Store NSDate
let date = NSDate()
try db.execute("INSERT INTO persons (date, ...) " +
"VALUES (?, ...)",
arguments: [DBDate(date), ...])
arguments: [DateTime(date), ...])
// Extract NSDate from row:
for rows in db.fetchRows("SELECT ...") {
let date = (row.value(named: "date") as DBDate?)?.date
let date = (row.value(named: "date") as DateTime?)?.date
}
// Direct fetch:
db.fetch(DBDate.self, "SELECT ...", arguments: ...) // AnySequence<DBDate?>
db.fetchAll(DBDate.self, "SELECT ...", arguments: ...) // [DBDate?]
db.fetchOne(DBDate.self, "SELECT ...", arguments: ...) // DBDate?
db.fetch(DateTime.self, "SELECT ...", arguments: ...) // AnySequence<DateTime?>
db.fetchAll(DateTime.self, "SELECT ...", arguments: ...) // [DateTime?]
db.fetchOne(DateTime.self, "SELECT ...", arguments: ...) // DateTime?
```
### Value Extraction in Details
+4
View File
@@ -3,6 +3,10 @@ Release Notes
## Future release
**New**
- `DateTime` performs ISO-8601 storage of NSDate in the database.
**Fixed**
- `RowModel.save(db)` calls `RowModel.insert(db)` or `RowModel.update(db)` so that eventual overridden versions of `insert` or `update` are invoked.
+1 -1
View File
@@ -1,3 +1,3 @@
- [ ] Remove RowModelError.Dummy when rdar://problem/21707972 is fixed.
- [ ] Make DBDate public, with a better name. Support ISO-8601 format, but document that comparison and sorting can't work with SQLite-generated values like CURRENT_TIMESTAMP.
- [ ] DateTime supports ISO-8601 format: document that comparison and sorting can't work with SQLite-generated values like CURRENT_TIMESTAMP.
- [ ] Test edited flag with Int property backed by a REAL database column.