diff --git a/CHANGELOG.md b/CHANGELOG.md index 41da8c04d..ffba504c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -160,6 +160,11 @@ Release Notes ``` +## Next Version + +- Improved parsing of dates and date components ([#334](https://github.com/groue/GRDB.swift/pull/334) by @sobri909) + + ## 2.10.0 Released March 30, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v2.9.0...v2.10.0) diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index ea6c98747..2f9e6cbb6 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -260,6 +260,7 @@ 566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; 566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; 566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; + 56707201208A509C006AD95A /* DateParsingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071FA208A509C006AD95A /* DateParsingTests.swift */; }; 567156181CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */; }; 5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; }; 5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; }; @@ -624,6 +625,9 @@ 56FF455A1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; 6340BF801E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */; }; 6340BF841E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */; }; + C96C0F2B2084A442006B2981 /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = C96C0F242084A442006B2981 /* SQLiteDateParser.swift */; }; + C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = C96C0F242084A442006B2981 /* SQLiteDateParser.swift */; }; + C96C0F2D2084A45A006B2981 /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = C96C0F242084A442006B2981 /* SQLiteDateParser.swift */; }; DC2393C81ABE35F8003FF113 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; DC3773F919C8CBB3004FCF85 /* GRDB.h in Headers */ = {isa = PBXBuildFile; fileRef = DC3773F819C8CBB3004FCF85 /* GRDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; /* End PBXBuildFile section */ @@ -839,6 +843,7 @@ 566B91221FA4CF810012D5B0 /* Database+Schema.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Schema.swift"; sourceTree = ""; }; 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = ""; }; 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = ""; }; + 567071FA208A509C006AD95A /* DateParsingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DateParsingTests.swift; sourceTree = ""; }; 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = ""; }; 567156701CB18050007DC145 /* EncryptionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncryptionTests.swift; sourceTree = ""; }; 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3TokenizerDescriptor.swift; sourceTree = ""; }; @@ -1026,6 +1031,7 @@ 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordDeleteTests.swift; sourceTree = ""; }; 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = ""; }; 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = ""; }; + C96C0F242084A442006B2981 /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = ""; }; DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = ""; }; DC3773F319C8CBB3004FCF85 /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; DC3773F719C8CBB3004FCF85 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; @@ -1133,6 +1139,7 @@ 5605F1521C672E4000235C62 /* NSString.swift */, 5657AB0E1D10899D006283EF /* URL.swift */, 56A8C22F1D1914540096E9D4 /* UUID.swift */, + C96C0F242084A442006B2981 /* SQLiteDateParser.swift */, ); path = Foundation; sourceTree = ""; @@ -1566,6 +1573,7 @@ 56DE7B361C42BBBB00861EB8 /* PerformanceCoreDataTests.sqlite */, 56DE7B2D1C42B23B00861EB8 /* PerformanceModel.xcdatamodeld */, 563363F81C960711000BE133 /* PerformanceRealmTests.realm */, + 567071FA208A509C006AD95A /* DateParsingTests.swift */, 56DE7B271C41302500861EB8 /* FetchNamedValuesTests.swift */, 56DE7B291C4130AF00861EB8 /* FetchPositionalValuesTests.swift */, 56DE7B2B1C41311900861EB8 /* FetchRecordClassTests.swift */, @@ -2128,6 +2136,7 @@ files = ( 56D3BE711F4EB1A00034C6D2 /* FetchRecordStructTests.swift in Sources */, 560C98231C0E23BB00BF8471 /* InsertRecordClassTests.swift in Sources */, + 56707201208A509C006AD95A /* DateParsingTests.swift in Sources */, 56DE7B2C1C41311900861EB8 /* FetchRecordClassTests.swift in Sources */, 56DE7B281C41302500861EB8 /* FetchNamedValuesTests.swift in Sources */, 56D507831F6D7B2E00AE1C5B /* InsertRecordStructTests.swift in Sources */, @@ -2194,6 +2203,7 @@ 565490D91D5AE252005622CB /* Migration.swift in Sources */, 56CEB5001EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD271DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, + C96C0F2D2084A45A006B2981 /* SQLiteDateParser.swift in Sources */, 566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, 565490D51D5AE252005622CB /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 565490C51D5AE236005622CB /* SerializedDatabase.swift in Sources */, @@ -2359,6 +2369,7 @@ 56D1215D1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 566AD8B51D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD241DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, + C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */, 5605F1681C672E4000235C62 /* NSNumber.swift in Sources */, 56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */, @@ -2759,6 +2770,7 @@ 56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */, 569A98ED2039B6F3008D7DBF /* Fixits-3.0.swift in Sources */, 5605F1671C672E4000235C62 /* NSNumber.swift in Sources */, + C96C0F2B2084A442006B2981 /* SQLiteDateParser.swift in Sources */, 56A238871B9C75030082EB20 /* Row.swift in Sources */, 5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */, 560D92471C672C4B00F4F92B /* PersistableRecord.swift in Sources */, diff --git a/GRDB.xcodeproj/xcshareddata/xcschemes/GRDBOSXPerformanceTests.xcscheme b/GRDB.xcodeproj/xcshareddata/xcschemes/GRDBOSXPerformanceTests.xcscheme index 2f1ecb6f3..4394516c3 100644 --- a/GRDB.xcodeproj/xcshareddata/xcschemes/GRDBOSXPerformanceTests.xcscheme +++ b/GRDB.xcodeproj/xcshareddata/xcschemes/GRDBOSXPerformanceTests.xcscheme @@ -10,6 +10,7 @@ buildConfiguration = "Release" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + language = "" shouldUseLaunchSchemeArgsEnv = "YES"> (OpaquePointer(sqlite3_column_text(sqliteStatement, index)!)) + let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen + guard let components = SQLiteDateParser().components(cString: cString, length: length) else { + fatalError("could not convert database value \(String(cString: cString)) to DatabaseDateComponents") + } + self.dateComponents = components.dateComponents + self.format = components.format + } // MARK: - DatabaseValueConvertible adoption @@ -131,158 +152,6 @@ public struct DatabaseDateComponents : DatabaseValueConvertible { return nil } - var dateComponents = DateComponents() - let scanner = Scanner(string: string) - scanner.charactersToBeSkipped = CharacterSet() - - let hasDate: Bool - - // YYYY or HH - var initialNumber: Int = 0 - if !scanner.scanInt(&initialNumber) { - return nil - } - switch scanner.scanLocation { - case 2: - // HH - hasDate = false - - let hour = initialNumber - if hour >= 0 && hour <= 23 { - dateComponents.hour = hour - } else { - return nil - } - - case 4: - // YYYY - hasDate = true - - let year = initialNumber - if year >= 0 && year <= 9999 { - dateComponents.year = year - } else { - return nil - } - - // - - if !scanner.scanString("-", into: nil) { - return nil - } - - // MM - var month: Int = 0 - if scanner.scanInt(&month) && month >= 1 && month <= 12 { - dateComponents.month = month - } else { - return nil - } - - // - - if !scanner.scanString("-", into: nil) { - return nil - } - - // DD - var day: Int = 0 - if scanner.scanInt(&day) && day >= 1 && day <= 31 { - dateComponents.day = day - } else { - return nil - } - - // YYYY-MM-DD - if scanner.isAtEnd { - return DatabaseDateComponents(dateComponents, format: .YMD) - } - - // T/space - if !scanner.scanString("T", into: nil) && !scanner.scanString(" ", into: nil) { - return nil - } - - // HH - var hour: Int = 0 - if scanner.scanInt(&hour) && hour >= 0 && hour <= 23 { - dateComponents.hour = hour - } else { - return nil - } - - default: - return nil - } - - // : - if !scanner.scanString(":", into: nil) { - return nil - } - - // MM - var minute: Int = 0 - if scanner.scanInt(&minute) && minute >= 0 && minute <= 59 { - dateComponents.minute = minute - } else { - return nil - } - - // [YYYY-MM-DD] HH:MM - if scanner.isAtEnd { - if hasDate { - return DatabaseDateComponents(dateComponents, format: .YMD_HM) - } else { - return DatabaseDateComponents(dateComponents, format: .HM) - } - } - - // : - if !scanner.scanString(":", into: nil) { - return nil - } - - // SS - var second: Int = 0 - if scanner.scanInt(&second) && second >= 0 && second <= 59 { - dateComponents.second = second - } else { - return nil - } - - // [YYYY-MM-DD] HH:MM:SS - if scanner.isAtEnd { - if hasDate { - return DatabaseDateComponents(dateComponents, format: .YMD_HMS) - } else { - return DatabaseDateComponents(dateComponents, format: .HMS) - } - } - - // . - if !scanner.scanString(".", into: nil) { - return nil - } - - // SSS - var millisecondDigits: NSString? = nil - if scanner.scanCharacters(from: .decimalDigits, into: &millisecondDigits), var millisecondDigits = millisecondDigits { - if millisecondDigits.length > 3 { - millisecondDigits = NSString(string: millisecondDigits.substring(to: 3)) - } - dateComponents.nanosecond = millisecondDigits.integerValue * 1_000_000 - } else { - return nil - } - - // [YYYY-MM-DD] HH:MM:SS.SSS - if scanner.isAtEnd { - if hasDate { - return DatabaseDateComponents(dateComponents, format: .YMD_HMSS) - } else { - return DatabaseDateComponents(dateComponents, format: .HMSS) - } - } - - // Unknown format - return nil + return SQLiteDateParser().components(from: string) } } diff --git a/GRDB/Core/Support/Foundation/Date.swift b/GRDB/Core/Support/Foundation/Date.swift index f19b0d935..78cdbbd30 100644 --- a/GRDB/Core/Support/Foundation/Date.swift +++ b/GRDB/Core/Support/Foundation/Date.swift @@ -1,4 +1,9 @@ import Foundation +#if SWIFT_PACKAGE + import CSQLite +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER + import SQLite3 +#endif /// NSDate is stored in the database using the format /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. @@ -108,6 +113,31 @@ extension Date : DatabaseValueConvertible { } } +extension Date: StatementColumnConvertible { + + /// Returns a value initialized from a raw SQLite statement pointer. + /// + /// - parameters: + /// - sqliteStatement: A pointer to an SQLite statement. + /// - index: The column index. + public init(sqliteStatement: SQLiteStatement, index: Int32) { + switch sqlite3_column_type(sqliteStatement, index) { + case SQLITE_INTEGER, SQLITE_FLOAT: + self.init(timeIntervalSince1970: sqlite3_column_double(sqliteStatement, Int32(index))) + case SQLITE_TEXT: + let databaseDateComponents = DatabaseDateComponents(sqliteStatement: sqliteStatement, index: index) + guard let date = Date(databaseDateComponents: databaseDateComponents) else { + let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index) + fatalError("could not convert database value \(dbValue) to Date") + } + self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate) + default: + let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index) + fatalError("could not convert database value \(dbValue) to Date") + } + } +} + /// The DatabaseDate date formatter for stored dates. private let storageDateFormatter: DateFormatter = { let formatter = DateFormatter() diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift new file mode 100644 index 000000000..8ac84c250 --- /dev/null +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -0,0 +1,140 @@ +import Foundation + +// inspired by: http://jordansmith.io/performant-date-parsing/ + +class SQLiteDateParser { + + private struct ParserComponents { + var year: Int32 = 0 + var month: Int32 = 0 + var day: Int32 = 0 + var hour: Int32 = 0 + var minute: Int32 = 0 + var second: Int32 = 0 + var nanosecond = ContiguousArray.init(repeating: 0, count: 10) // 9 digits, and trailing \0 + } + + func components(from dateString: String) -> DatabaseDateComponents? { + return dateString.withCString { cString in + components(cString: cString, length: strlen(cString)) + } + } + + func components(cString: UnsafePointer, length: Int) -> DatabaseDateComponents? { + assert(strlen(cString) == length) + + guard length >= 5 else { return nil } + + if cString.advanced(by: 4).pointee == 45 /* '-' */ { + return datetimeComponents(cString: cString, length: length) + } + + if cString.advanced(by: 2).pointee == 58 /* ':' */ { + return timeComponents(cString: cString, length: length) + } + + return nil + } + + // - YYYY-MM-DD + // - YYYY-MM-DD HH:MM + // - YYYY-MM-DD HH:MM:SS + // - YYYY-MM-DD HH:MM:SS.SSS + // - YYYY-MM-DDTHH:MM + // - YYYY-MM-DDTHH:MM:SS + // - YYYY-MM-DDTHH:MM:SS.SSS + private func datetimeComponents(cString: UnsafePointer, length: Int) -> DatabaseDateComponents? { + var parserComponents = ParserComponents() + + // TODO: Get rid of this pyramid when SE-0210 has shipped + let parseCount = withUnsafeMutablePointer(to: &parserComponents.year) { yearP in + withUnsafeMutablePointer(to: &parserComponents.month) { monthP in + withUnsafeMutablePointer(to: &parserComponents.day) { dayP in + withUnsafeMutablePointer(to: &parserComponents.hour) { hourP in + withUnsafeMutablePointer(to: &parserComponents.minute) { minuteP in + withUnsafeMutablePointer(to: &parserComponents.second) { secondP in + parserComponents.nanosecond.withUnsafeMutableBufferPointer { nanosecondBuffer in + withVaList([yearP, monthP, dayP, hourP, minuteP, secondP, nanosecondBuffer.baseAddress!]) { pointer in + vsscanf(cString, "%4d-%2d-%2d%*1[ T]%2d:%2d:%2d.%10s", pointer) + } + } + } + } + } + } + } + } + + guard parseCount >= 3 else { return nil } + + var components = DateComponents() + components.year = Int(parserComponents.year) + components.month = Int(parserComponents.month) + components.day = Int(parserComponents.day) + + guard parseCount >= 5 else { return DatabaseDateComponents(components, format: .YMD) } + + components.hour = Int(parserComponents.hour) + components.minute = Int(parserComponents.minute) + + guard parseCount >= 6 else { return DatabaseDateComponents(components, format: .YMD_HM) } + + components.second = Int(parserComponents.second) + + guard parseCount >= 7 else { return DatabaseDateComponents(components, format: .YMD_HMS) } + + components.nanosecond = nanosecondsInt(for: parserComponents.nanosecond) + + return DatabaseDateComponents(components, format: .YMD_HMSS) + } + + // - HH:MM + // - HH:MM:SS + // - HH:MM:SS.SSS + private func timeComponents(cString: UnsafePointer, length: Int) -> DatabaseDateComponents? { + var parserComponents = ParserComponents() + + // TODO: Get rid of this pyramid when SE-0210 has shipped + let parseCount = withUnsafeMutablePointer(to: &parserComponents.hour) { hourP in + withUnsafeMutablePointer(to: &parserComponents.minute) { minuteP in + withUnsafeMutablePointer(to: &parserComponents.second) { secondP in + parserComponents.nanosecond.withUnsafeMutableBufferPointer { nanosecondBuffer in + withVaList([hourP, minuteP, secondP, nanosecondBuffer.baseAddress!]) { pointer in + vsscanf(cString, "%2d:%2d:%2d.%10s", pointer) + } + } + } + } + } + + guard parseCount >= 2 else { return nil } + + var components = DateComponents() + components.hour = Int(parserComponents.hour) + components.minute = Int(parserComponents.minute) + + guard parseCount >= 3 else { return DatabaseDateComponents(components, format: .HM) } + + components.second = Int(parserComponents.second) + + guard parseCount >= 4 else { return DatabaseDateComponents(components, format: .HMS) } + + guard let nanoseconds = nanosecondsInt(for: parserComponents.nanosecond) else { return nil } + components.nanosecond = nanoseconds + + return DatabaseDateComponents(components, format: .HMSS) + } + + private func nanosecondsInt(for nanosecond: ContiguousArray) -> Int? { + // truncate after the third digit + var result = 0 + let multipliers = [100_000_000, 10_000_000, 1_000_000, 100_000, 10_000, 1_000, 100, 10, 1] + for (char, multiplier) in zip(nanosecond.prefix(3), multipliers) { + if char == 0 { return result } + let digit = Int(char) - 48 /* '0' */ + guard (0...9).contains(digit) else { return nil } + result += multiplier * digit + } + return result + } +} diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index d03e81f71..47e583fe3 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -282,6 +282,8 @@ 566B912F1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; }; 566B91341FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; 566B91371FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; + 567071F8208A00D4006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F6208A00D4006AD95A /* SQLiteDateParser.swift */; }; + 567071F9208A00D4006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F6208A00D4006AD95A /* SQLiteDateParser.swift */; }; 567156141CB141D0007DC145 /* DatabaseQueueInMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */; }; 567156171CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */; }; 5671561D1CB16729007DC145 /* DatabaseValueConversionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */; }; @@ -913,6 +915,7 @@ 566B91221FA4CF810012D5B0 /* Database+Schema.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Schema.swift"; sourceTree = ""; }; 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = ""; }; 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = ""; }; + 567071F6208A00D4006AD95A /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = ""; }; 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = ""; }; 5671566C1CB16729007DC145 /* GRDBCipherOSXEncryptedTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCipherOSXEncryptedTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 567156701CB18050007DC145 /* EncryptionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncryptionTests.swift; sourceTree = ""; }; @@ -1161,6 +1164,7 @@ 5605F1521C672E4000235C62 /* NSString.swift */, 5657AB0E1D10899D006283EF /* URL.swift */, 56A8C22F1D1914540096E9D4 /* UUID.swift */, + 567071F6208A00D4006AD95A /* SQLiteDateParser.swift */, ); path = Foundation; sourceTree = ""; @@ -2063,6 +2067,7 @@ 560FC53C1CB003810014AA8E /* DatabaseQueue.swift in Sources */, 569A98FC2039B72D008D7DBF /* Fixits-3.0.swift in Sources */, 560FC53D1CB003810014AA8E /* NSNumber.swift in Sources */, + 567071F8208A00D4006AD95A /* SQLiteDateParser.swift in Sources */, 560FC53F1CB003810014AA8E /* Row.swift in Sources */, 560FC5401CB003810014AA8E /* StandardLibrary.swift in Sources */, 560FC5411CB003810014AA8E /* PersistableRecord.swift in Sources */, @@ -2456,6 +2461,7 @@ 569A98FD2039B72D008D7DBF /* Fixits-3.0.swift in Sources */, 56AFCA141CB1A8BB00F48B96 /* StandardLibrary.swift in Sources */, 56AFCA151CB1A8BB00F48B96 /* PersistableRecord.swift in Sources */, + 567071F9208A00D4006AD95A /* SQLiteDateParser.swift in Sources */, 56AFCA161CB1A8BB00F48B96 /* StatementColumnConvertible.swift in Sources */, 566475A61D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABD1D107001006283EF /* NSData.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index d96f277b3..b76869c92 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -111,6 +111,8 @@ 566B91301FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; }; 566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; 566B91381FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; + 567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */; }; + 567071F5208A00BE006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */; }; 5671FC221DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; }; 5671FC251DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; }; 56741EAB1E66A8B3003E422D /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */; }; @@ -616,6 +618,7 @@ 566B91221FA4CF810012D5B0 /* Database+Schema.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Schema.swift"; sourceTree = ""; }; 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = ""; }; 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = ""; }; + 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = ""; }; 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = ""; }; 567156701CB18050007DC145 /* EncryptionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncryptionTests.swift; sourceTree = ""; }; 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3TokenizerDescriptor.swift; sourceTree = ""; }; @@ -852,6 +855,7 @@ 5605F1521C672E4000235C62 /* NSString.swift */, 5657AB0E1D10899D006283EF /* URL.swift */, 56A8C22F1D1914540096E9D4 /* UUID.swift */, + 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */, ); path = Foundation; sourceTree = ""; @@ -1769,6 +1773,7 @@ 569A98F92039B716008D7DBF /* Fixits-3.0.swift in Sources */, F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */, F3BA80361CFB28A4003DC1BA /* TableRecord.swift in Sources */, + 567071F5208A00BE006AD95A /* SQLiteDateParser.swift in Sources */, F3BA80271CFB2891003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 566475A71D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABE1D107001006283EF /* NSData.swift in Sources */, @@ -2015,6 +2020,7 @@ 569A98F82039B716008D7DBF /* Fixits-3.0.swift in Sources */, F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */, F3BA80921CFB2E7A003DC1BA /* TableRecord.swift in Sources */, + 567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */, F3BA80831CFB2E67003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 566475A41D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABB1D107001006283EF /* NSData.swift in Sources */, diff --git a/README.md b/README.md index f0e3dc642..db383139d 100644 --- a/README.md +++ b/README.md @@ -7084,7 +7084,7 @@ Sample Code **Thanks** - [Pierlis](http://pierlis.com), where we write great software. -- [Vladimir Babin](https://github.com/Chiliec), [Darren Clark](https://github.com/darrenclark), [Pascal Edmond](https://github.com/pakko972), [Andrey Fidrya](https://github.com/zmeyc), [Cristian Filipov](https://github.com/cfilipov), [David Hart](https://github.com/hartbit), [Brad Lindsay](https://github.com/bfad), [@peter-ss](https://github.com/peter-ss), [Pierre-Loïc Raynaud](https://github.com/pierlo), [Stefano Rodriguez](https://github.com/sroddy) [Steven Schveighoffer](https://github.com/schveiguy), [@swiftlyfalling](https://github.com/swiftlyfalling), and [Kevin Wooten](https://github.com/kdubb) for their contributions, help, and feedback on GRDB. +- [Vladimir Babin](https://github.com/Chiliec), [Darren Clark](https://github.com/darrenclark), [Pascal Edmond](https://github.com/pakko972), [Andrey Fidrya](https://github.com/zmeyc), [Cristian Filipov](https://github.com/cfilipov), [Matt Greenfield](https://github.com/sobri909), [David Hart](https://github.com/hartbit), [Brad Lindsay](https://github.com/bfad), [@peter-ss](https://github.com/peter-ss), [Pierre-Loïc Raynaud](https://github.com/pierlo), [Stefano Rodriguez](https://github.com/sroddy) [Steven Schveighoffer](https://github.com/schveiguy), [@swiftlyfalling](https://github.com/swiftlyfalling), and [Kevin Wooten](https://github.com/kdubb) for their contributions, help, and feedback on GRDB. - [@aymerick](https://github.com/aymerick) and [Mathieu "Kali" Poumeyrol](https://github.com/kali) because SQL. - [ccgus/fmdb](https://github.com/ccgus/fmdb) for its excellency. diff --git a/Tests/GRDBTests/FoundationDateComponentsTests.swift b/Tests/GRDBTests/FoundationDateComponentsTests.swift index 7edceb270..417a2af69 100644 --- a/Tests/GRDBTests/FoundationDateComponentsTests.swift +++ b/Tests/GRDBTests/FoundationDateComponentsTests.swift @@ -354,6 +354,156 @@ class FoundationDateComponentsTests : GRDBTestCase { } } + func testDatabaseDateComponentsParsing() { + func assertParse(_ string: String, _ dateComponent: DatabaseDateComponents, file: StaticString = #file, line: UInt = #line) { + do { + // Test DatabaseValueConvertible adoption + let parsed = DatabaseDateComponents.fromDatabaseValue(string.databaseValue)! + XCTAssertEqual(parsed.format, dateComponent.format, file: file, line: line) + XCTAssertEqual(parsed.dateComponents, dateComponent.dateComponents, file: file, line: line) + } + do { + // Test StatementColumnConvertible adoption + let parsed = DatabaseQueue().inDatabase { + try! DatabaseDateComponents.fetchOne($0, "SELECT ?", arguments: [string])! + } + XCTAssertEqual(parsed.format, dateComponent.format, file: file, line: line) + XCTAssertEqual(parsed.dateComponents, dateComponent.dateComponents, file: file, line: line) + } + } + + assertParse( + "0000-01-01", + DatabaseDateComponents( + DateComponents(year: 0, month: 1, day: 1, hour: nil, minute: nil, second: nil, nanosecond: nil), + format: .YMD)!) + assertParse( + "2018-12-31", + DatabaseDateComponents( + DateComponents(year: 2018, month: 12, day: 31, hour: nil, minute: nil, second: nil, nanosecond: nil), + format: .YMD)!) + assertParse( + "2018-04-21 00:00", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: nil, nanosecond: nil), + format: .YMD_HM)!) + assertParse( + "2018-04-21T23:59", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: nil, nanosecond: nil), + format: .YMD_HM)!) + assertParse( + "2018-04-21 00:00:00", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: nil), + format: .YMD_HMS)!) + assertParse( + "2018-04-21T23:59:59", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: nil), + format: .YMD_HMS)!) + assertParse( + "2018-04-21 00:00:00.0", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 0), + format: .YMD_HMSS)!) + assertParse( + "2018-04-21T23:59:59.9", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 900_000_000), + format: .YMD_HMSS)!) + assertParse( + "2018-04-21 00:00:00.00", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 0), + format: .YMD_HMSS)!) + assertParse( + "2018-04-21 00:00:00.01", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 10_000_000), + format: .YMD_HMSS)!) + assertParse( + "2018-04-21T23:59:59.99", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 990_000_000), + format: .YMD_HMSS)!) + assertParse( + "2018-04-21 00:00:00.000", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 0), + format: .YMD_HMSS)!) + assertParse( + "2018-04-21 00:00:00.001", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 1_000_000), + format: .YMD_HMSS)!) + assertParse( + "2018-04-21T23:59:59.999", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), + format: .YMD_HMSS)!) + assertParse( + "00:00", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: nil, nanosecond: nil), + format: .HM)!) + assertParse( + "23:59", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: nil, nanosecond: nil), + format: .HM)!) + assertParse( + "00:00:00", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: nil), + format: .HMS)!) + assertParse( + "23:59:59", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: nil), + format: .HMS)!) + assertParse( + "00:00:00.0", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 0), + format: .HMSS)!) + assertParse( + "23:59:59.9", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 900_000_000), + format: .HMSS)!) + assertParse( + "00:00:00.00", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 0), + format: .HMSS)!) + assertParse( + "00:00:00.01", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 10_000_000), + format: .HMSS)!) + assertParse( + "23:59:59.99", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 990_000_000), + format: .HMSS)!) + assertParse( + "00:00:00.000", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 0), + format: .HMSS)!) + assertParse( + "00:00:00.001", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 1_000_000), + format: .HMSS)!) + assertParse( + "23:59:59.999", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), + format: .HMSS)!) + } + func testDatabaseDateComponentsFromUnparsableString() { let databaseDateComponents = DatabaseDateComponents.fromDatabaseValue("foo".databaseValue) XCTAssertTrue(databaseDateComponents == nil) diff --git a/Tests/Performance/DateParsingTests.swift b/Tests/Performance/DateParsingTests.swift new file mode 100644 index 000000000..35d74cf09 --- /dev/null +++ b/Tests/Performance/DateParsingTests.swift @@ -0,0 +1,35 @@ +import XCTest +import GRDB + +class DateParsingTests: XCTestCase { + + /// Selects many dates + let request = """ + WITH RECURSIVE + cnt(x) AS ( + SELECT 1 + UNION ALL + SELECT x+1 FROM cnt + LIMIT 50000 + ) + SELECT '2018-04-20 14:47:12.345' FROM cnt; + """ + + func testParseDateComponents() { + measure { + try! DatabaseQueue().inDatabase { db in + let cursor = try DatabaseDateComponents.fetchCursor(db, request) + while try cursor.next() != nil { } + } + } + } + + func testParseDate() { + measure { + try! DatabaseQueue().inDatabase { db in + let cursor = try Date.fetchCursor(db, request) + while try cursor.next() != nil { } + } + } + } +}