From d94fcc398b276dbe3bd42e839779b9c14b91f114 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Jun 2020 20:48:12 +0200 Subject: [PATCH] Date modifiers, more julianDay(), and dateTime() --- CHANGELOG.md | 7 ++ GRDB/QueryInterface/SQL/SQLFunctions.swift | 91 +++++++++++++++++++- README.md | 9 +- Tests/GRDBTests/FoundationDateTests.swift | 97 ++++++++++++++++++++-- 4 files changed, 193 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b77ab6d85..94d2281e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -70,7 +70,14 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Next Release +### Documentation Diff + +- The [SQL Functions](README.md#sql-functions) chapter was updated for the new `julianDay` and `dateTime` functions. + +### New + - [#794](https://github.com/groue/GRDB.swift/pull/794): Name of Database Connections +- Add the `julianDay` and `dateTime` functions ## 5.0.0-beta.3 diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index 5d95d2b86..63b0bb615 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -217,6 +217,68 @@ extension SQLSpecificExpressible { // MARK: - Date functions +/// A date modifier for SQLite date functions. +/// +/// For more information, see https://www.sqlite.org/lang_datefunc.html +public enum SQLDateModifier: SQLExpression { + case day(Int) + case hour(Int) + case minute(Int) + case second(Double) + case month(Int) + case year(Int) + case startOfMonth + case startOfYear + case startOfDay + case weekday(Int) + case unixEpoch + case localTime + case utc + + var rawValue: String { + switch self { + case let .day(value): + return "\(value) days" + case let .hour(value): + return "\(value) hours" + case let .minute(value): + return "\(value) minutes" + case let .second(value): + return "\(value) seconds" + case let .month(value): + return "\(value) months" + case let .year(value): + return "\(value) years" + case .startOfMonth: + return "start of month" + case .startOfYear: + return "start of year" + case .startOfDay: + return "start of day" + case let .weekday(value): + return "weekday \(value)" + case .unixEpoch: + return "unixepoch" + case .localTime: + return "localtime" + case .utc: + return "utc" + } + } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + try rawValue.databaseValue.expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis) + } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + self + } +} + // MARK: JULIANDAY(...) extension SQLFunctionName { @@ -228,6 +290,31 @@ extension SQLFunctionName { /// /// // JULIANDAY(date) /// julianDay(Column("date")) -public func julianDay(_ value: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionFunction(.julianDay, arguments: value) +/// +/// // JULIANDAY(date, '1 days') +/// julianDay(Column("date"), .day(1)) +/// +/// For more information, see https://www.sqlite.org/lang_datefunc.html +public func julianDay(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression { + SQLExpressionFunction(.julianDay, arguments: [value.sqlExpression] + modifiers) +} + +// MARK: DATETIME(...) + +extension SQLFunctionName { + /// The `DATETIME` function name + public static let dateTime = SQLFunctionName("DATETIME") +} + +/// Returns an expression that evaluates the `DATETIME` SQL function. +/// +/// // DATETIME(date) +/// dateTime(Column("date")) +/// +/// // DATETIME(date, '1 days') +/// dateTime(Column("date"), .day(1)) +/// +/// For more information, see https://www.sqlite.org/lang_datefunc.html +public func dateTime(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression { + SQLExpressionFunction(.dateTime, arguments: [value.sqlExpression] + modifiers) } diff --git a/README.md b/README.md index f553fc4de..8d6f2f140 100644 --- a/README.md +++ b/README.md @@ -4416,9 +4416,9 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: ### SQL Functions -- `ABS`, `AVG`, `COUNT`, `JULIANDAY`, `LENGTH`, `MAX`, `MIN`, `SUM`: +- `ABS`, `AVG`, `COUNT`, `DATETIME`, `JULIANDAY`, `LENGTH`, `MAX`, `MIN`, `SUM`: - Those are based on the `abs`, `average`, `count`, `julianDay`, `length`, `max`, `min` and `sum` Swift functions: + Those are based on the `abs`, `average`, `count`, `dateTime`, `julianDay`, `length`, `max`, `min` and `sum` Swift functions: ```swift // SELECT MIN(score), MAX(score) FROM player @@ -4429,7 +4429,12 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: // SELECT COUNT(DISTINCT name) FROM player Player.select(count(distinct: nameColumn)) + + // SELECT JULIANDAY(date, 'start of year') FROM game + Game.select(julianday(dateColumn, .startOfYear)) ``` + + For more information about the functions `dateTime` and `julianDay`, see [Date And Time Functions](https://www.sqlite.org/lang_datefunc.html). - `IFNULL` diff --git a/Tests/GRDBTests/FoundationDateTests.swift b/Tests/GRDBTests/FoundationDateTests.swift index dd36d0efc..51d087438 100644 --- a/Tests/GRDBTests/FoundationDateTests.swift +++ b/Tests/GRDBTests/FoundationDateTests.swift @@ -258,15 +258,98 @@ class FoundationDateTests : GRDBTestCase { } func testJulianDaySQLFunction() throws { + // 00:30:00.0 UT January 1, 2013 according to https://en.wikipedia.org/wiki/Julian_day + let jdn = 2_456_293.520833 + guard let date = Date(julianDay: jdn) else { + XCTFail() + return + } + + func assert( + _ db: Database, + _ expression: SQLExpression, + equal expectedDate: Date, + file: StaticString = #file, + line: UInt = #line) throws + { + let request: SQLRequest = "SELECT \(expression)" + guard let shiftedDate = try request.fetchOne(db).flatMap(Date.init(julianDay:)) else { + XCTFail(file: file, line: line) + return + } + let shiftedInterval = shiftedDate.timeIntervalSince(date) + let expectedInterval = expectedDate.timeIntervalSince(date) + XCTAssertEqual(shiftedInterval, expectedInterval, accuracy: 0.1, file: file, line: line) + } + let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - try db.execute( - sql: "INSERT INTO dates (creationDate) VALUES (?)", - arguments: ["2013-01-01T00:29:59"]) - let expression = julianDay(Column("creationDate")) - let request: SQLRequest = "SELECT \(expression) from dates" - let double = try request.fetchOne(db)! - XCTAssertEqual(double, 2456293.5208217595) + let dbDate = date.databaseValue + try assert(db, julianDay(dbDate), equal: date) + try assert(db, julianDay(dbDate, .day(1)), equal: date.addingTimeInterval(86400)) + try assert(db, julianDay(dbDate, .day(-1)), equal: date.addingTimeInterval(-86400)) + try assert(db, julianDay(dbDate, .hour(1)), equal: date.addingTimeInterval(3600)) + try assert(db, julianDay(dbDate, .hour(-1)), equal: date.addingTimeInterval(-3600)) + try assert(db, julianDay(dbDate, .minute(1)), equal: date.addingTimeInterval(60)) + try assert(db, julianDay(dbDate, .minute(-1)), equal: date.addingTimeInterval(-60)) + try assert(db, julianDay(dbDate, .second(1)), equal: date.addingTimeInterval(1)) + try assert(db, julianDay(dbDate, .second(-1)), equal: date.addingTimeInterval(-1)) + try assert(db, julianDay(dbDate, .second(1.5)), equal: date.addingTimeInterval(1.5)) + try assert(db, julianDay(dbDate, .month(1)), equal: date.addingTimeInterval(2678400)) + try assert(db, julianDay(dbDate, .month(-1)), equal: date.addingTimeInterval(-2678400)) + try assert(db, julianDay(dbDate, .year(1)), equal: date.addingTimeInterval(31536000)) + try assert(db, julianDay(dbDate, .year(-1)), equal: date.addingTimeInterval(-31622400)) + try assert(db, julianDay(dbDate, .startOfDay), equal: date.addingTimeInterval(-1800)) + try assert(db, julianDay(dbDate, .startOfMonth), equal: date.addingTimeInterval(-1800)) + try assert(db, julianDay(dbDate, .startOfYear), equal: date.addingTimeInterval(-1800)) + try assert(db, julianDay(dbDate, .startOfMonth, .month(+1), .day(-1)), equal: date.addingTimeInterval(2590200)) + } + } + + func testDateTimeSQLFunction() throws { + // 00:30:00.0 UT January 1, 2013 according to https://en.wikipedia.org/wiki/Julian_day + let jdn = 2_456_293.520833 + guard let date = Date(julianDay: jdn) else { + XCTFail() + return + } + + func assert( + _ db: Database, + _ expression: SQLExpression, + equal expectedDate: String, + file: StaticString = #file, + line: UInt = #line) throws + { + let request: SQLRequest = "SELECT \(expression)" + guard let shiftedDate = try request.fetchOne(db) else { + XCTFail(file: file, line: line) + return + } + XCTAssertEqual(shiftedDate, expectedDate, file: file, line: line) + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let dbDate = date.databaseValue + try assert(db, dateTime(dbDate), equal: "2013-01-01 00:29:59") + try assert(db, dateTime(dbDate, .day(1)), equal: "2013-01-02 00:29:59") + try assert(db, dateTime(dbDate, .day(-1)), equal: "2012-12-31 00:29:59") + try assert(db, dateTime(dbDate, .hour(1)), equal: "2013-01-01 01:29:59") + try assert(db, dateTime(dbDate, .hour(-1)), equal: "2012-12-31 23:29:59") + try assert(db, dateTime(dbDate, .minute(1)), equal: "2013-01-01 00:30:59") + try assert(db, dateTime(dbDate, .minute(-1)), equal: "2013-01-01 00:28:59") + try assert(db, dateTime(dbDate, .second(1)), equal: "2013-01-01 00:30:00") + try assert(db, dateTime(dbDate, .second(-1)), equal: "2013-01-01 00:29:58") + try assert(db, dateTime(dbDate, .second(1.5)), equal: "2013-01-01 00:30:01") + try assert(db, dateTime(dbDate, .month(1)), equal: "2013-02-01 00:29:59") + try assert(db, dateTime(dbDate, .month(-1)), equal: "2012-12-01 00:29:59") + try assert(db, dateTime(dbDate, .year(1)), equal: "2014-01-01 00:29:59") + try assert(db, dateTime(dbDate, .year(-1)), equal: "2012-01-01 00:29:59") + try assert(db, dateTime(dbDate, .startOfDay), equal: "2013-01-01 00:00:00") + try assert(db, dateTime(dbDate, .startOfMonth), equal: "2013-01-01 00:00:00") + try assert(db, dateTime(dbDate, .startOfYear), equal: "2013-01-01 00:00:00") + try assert(db, dateTime(dbDate, .startOfMonth, .month(+1), .day(-1)), equal: "2013-01-31 00:00:00") } } }