From 98dc15ff5128f9fd7656befeaa81493fd2c686b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 21 Jul 2015 15:06:56 +0200 Subject: [PATCH] Public support for NSDate through DateTime --- GRDB Tests/GRDBTestCase.swift | 49 ------------ ...{DBDateTests.swift => DateTimeTests.swift} | 10 +-- .../RowModel/PrimaryKeyRowIDTests.swift | 4 +- GRDB.xcodeproj/project.pbxproj | 18 +++-- GRDB/DateTime.swift | 74 +++++++++++++++++++ README.md | 24 +++--- RELEASE_NOTES.md | 4 + TODO.md | 2 +- 8 files changed, 110 insertions(+), 75 deletions(-) rename GRDB Tests/Public/DatabaseValueConvertible/{DBDateTests.swift => DateTimeTests.swift} (94%) create mode 100644 GRDB/DateTime.swift diff --git a/GRDB Tests/GRDBTestCase.swift b/GRDB Tests/GRDBTestCase.swift index 91c513988..96c872123 100644 --- a/GRDB Tests/GRDBTestCase.swift +++ b/GRDB Tests/GRDBTestCase.swift @@ -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! diff --git a/GRDB Tests/Public/DatabaseValueConvertible/DBDateTests.swift b/GRDB Tests/Public/DatabaseValueConvertible/DateTimeTests.swift similarity index 94% rename from GRDB Tests/Public/DatabaseValueConvertible/DBDateTests.swift rename to GRDB Tests/Public/DatabaseValueConvertible/DateTimeTests.swift index 6d4f6bf4d..88d446f60 100644 --- a/GRDB Tests/Public/DatabaseValueConvertible/DBDateTests.swift +++ b/GRDB Tests/Public/DatabaseValueConvertible/DateTimeTests.swift @@ -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) diff --git a/GRDB Tests/Public/RowModel/PrimaryKeyRowIDTests.swift b/GRDB Tests/Public/RowModel/PrimaryKeyRowIDTests.swift index 361212ce6..930e98f56 100644 --- a/GRDB Tests/Public/RowModel/PrimaryKeyRowIDTests.swift +++ b/GRDB Tests/Public/RowModel/PrimaryKeyRowIDTests.swift @@ -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) } } diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 544203889..9d14e5e60 100644 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -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 = ""; }; + 5645E69C1B5E76D30045DC8F /* DateTime.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DateTime.swift; sourceTree = ""; }; 564E0B131B4D8FC100EBC9F6 /* DatabaseError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseError.swift; sourceTree = ""; }; 564E0B151B4D901300EBC9F6 /* DatabaseValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValue.swift; sourceTree = ""; }; 565E191D1B42B2B600D32814 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = ""; }; @@ -125,7 +128,7 @@ 569979681B539038005EBEED /* InMemoryDatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InMemoryDatabaseTests.swift; sourceTree = ""; }; 5699796A1B539038005EBEED /* DatabaseErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseErrorTests.swift; sourceTree = ""; }; 5699796C1B539038005EBEED /* DatabaseMigratorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseMigratorTests.swift; sourceTree = ""; }; - 5699796E1B539038005EBEED /* DBDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DBDateTests.swift; sourceTree = ""; }; + 5699796E1B539038005EBEED /* DateTimeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DateTimeTests.swift; sourceTree = ""; }; 5699796F1B539038005EBEED /* DatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleTests.swift; sourceTree = ""; }; 569979701B539038005EBEED /* RawRepresentableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RawRepresentableTests.swift; sourceTree = ""; }; 569979731B539038005EBEED /* FetchedRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRowTests.swift; sourceTree = ""; }; @@ -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 */, diff --git a/GRDB/DateTime.swift b/GRDB/DateTime.swift new file mode 100644 index 000000000..1390bff54 --- /dev/null +++ b/GRDB/DateTime.swift @@ -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 + } + } +} + diff --git a/README.md b/README.md index 21a81345b..8dbe43c8e 100644 --- a/README.md +++ b/README.md @@ -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 -db.fetchAll(DBDate.self, "SELECT ...", arguments: ...) // [DBDate?] -db.fetchOne(DBDate.self, "SELECT ...", arguments: ...) // DBDate? +db.fetch(DateTime.self, "SELECT ...", arguments: ...) // AnySequence +db.fetchAll(DateTime.self, "SELECT ...", arguments: ...) // [DateTime?] +db.fetchOne(DateTime.self, "SELECT ...", arguments: ...) // DateTime? ``` ### Value Extraction in Details diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 763550e85..dd910444e 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -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. diff --git a/TODO.md b/TODO.md index 7593b8a96..3a719406b 100644 --- a/TODO.md +++ b/TODO.md @@ -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.