Decode UUID and NSUUID from both blobs and strings

This commit is contained in:
Gwendal Roué committed 2018-08-20 21:13:58 +02:00
1 parent c6b1872291
commit fb209d8805
4 files changed
+131 -75

No files matched your search

+53 -8
View File
@@ -2,9 +2,7 @@ import Foundation
#if !os(Linux)
/// NSUUID adopts DatabaseValueConvertible
extension NSUUID : DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
extension NSUUID: DatabaseValueConvertible {
public var databaseValue: DatabaseValue {
var uuidBytes = ContiguousArray(repeating: UInt8(0), count: 16)
return uuidBytes.withUnsafeMutableBufferPointer { buffer in
@@ -13,15 +11,62 @@ extension NSUUID : DatabaseValueConvertible {
}
}
/// Returns an NSUUID initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
guard let data = NSData.fromDatabaseValue(dbValue), data.length == 16 else {
switch dbValue.storage {
case .blob(let data) where data.count == 16:
return data.withUnsafeBytes {
self.init(uuidBytes: $0)
}
case .string(let string):
return self.init(uuidString: string)
default:
return nil
}
return self.init(uuidBytes: data.bytes.assumingMemoryBound(to: UInt8.self))
}
}
}
#endif
/// UUID adopts DatabaseValueConvertible
extension UUID : DatabaseValueConvertible { }
extension UUID: DatabaseValueConvertible {
public var databaseValue: DatabaseValue {
var uuid_t = uuid
return withUnsafeBytes(of: &uuid_t) {
Data(bytes: $0.baseAddress!, count: $0.count).databaseValue
}
}
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UUID? {
switch dbValue.storage {
case .blob(let data) where data.count == 16:
return data.withUnsafeBytes {
UUID(uuid: $0.pointee)
}
case .string(let string):
return UUID(uuidString: string)
default:
return nil
}
}
}
extension UUID: StatementColumnConvertible {
public init(sqliteStatement: SQLiteStatement, index: Int32) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_TEXT:
let string = String(cString: sqlite3_column_text(sqliteStatement, index)!)
guard let uuid = UUID(uuidString: string) else {
fatalConversionError(to: UUID.self, sqliteStatement: sqliteStatement, index: index)
}
self.init(uuid: uuid.uuid)
case SQLITE_BLOB:
guard sqlite3_column_bytes(sqliteStatement, index) == 16,
let blob = sqlite3_column_blob(sqliteStatement, index) else
{
fatalConversionError(to: UUID.self, sqliteStatement: sqliteStatement, index: index)
}
self.init(uuid: blob.assumingMemoryBound(to: uuid_t.self).pointee)
default:
fatalConversionError(to: UUID.self, sqliteStatement: sqliteStatement, index: index)
}
}
}
+3 -1
View File
@@ -1313,7 +1313,9 @@ let amount = NSDecimalNumber(value: integerAmount).multiplying(byPowerOf10: -2)
### UUID
**UUID** can be stored and fetched from the database just like other [values](#values). GRDB stores uuids as 16-bytes data blobs.
**UUID** can be stored and fetched from the database just like other [values](#values).
GRDB stores uuids as 16-bytes data blobs, and decodes them from both 16-bytes data blobs and strings such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F".
### Swift Enums
+37 -33
View File
@@ -8,47 +8,51 @@ import XCTest
#endif
class FoundationNSUUIDTests: GRDBTestCase {
func testNSUUIDDatabaseRoundTrip() throws {
let dbQueue = try makeDatabaseQueue()
func roundTrip(_ value: NSUUID) throws -> Bool {
guard let back = try dbQueue.inDatabase({ try NSUUID.fetchOne($0, "SELECT ?", arguments: [value]) }) else {
XCTFail()
return false
private func assert(_ value: DatabaseValueConvertible?, isDecodedAs expectedUUID: NSUUID?) throws {
try makeDatabaseQueue().read { db in
if let expectedUUID = expectedUUID {
let decodedUUID = try NSUUID.fetchOne(db, "SELECT ?", arguments: [value])
XCTAssertEqual(decodedUUID, expectedUUID)
} else if value == nil {
let decodedUUID = try Optional<NSUUID>.fetchAll(db, "SELECT NULL")[0]
XCTAssertNil(decodedUUID)
}
return back == value
}
XCTAssertTrue(try roundTrip(NSUUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!))
XCTAssertTrue(try roundTrip(NSUUID()))
let decodedUUID = NSUUID.fromDatabaseValue(value?.databaseValue ?? .null)
XCTAssertEqual(decodedUUID, expectedUUID)
}
func testNSUUIDDatabaseValueRoundTrip() {
func roundTrip(_ value: NSUUID) -> Bool {
let dbValue = value.databaseValue
guard let back = NSUUID.fromDatabaseValue(dbValue) else {
XCTFail("Failed to convert from DatabaseValue to NSUUID")
return false
}
return back.isEqual(value)
private func assertRoundTrip(_ uuid: UUID) throws {
let string = uuid.uuidString
var uuid_t = uuid.uuid
let data = withUnsafeBytes(of: &uuid_t) {
Data(bytes: $0.baseAddress!, count: $0.count)
}
XCTAssertTrue(roundTrip(NSUUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!))
XCTAssertTrue(roundTrip(NSUUID()))
try assert(string, isDecodedAs: uuid as NSUUID)
try assert(string.lowercased(), isDecodedAs: uuid as NSUUID)
try assert(string.uppercased(), isDecodedAs: uuid as NSUUID)
try assert(uuid, isDecodedAs: uuid as NSUUID)
try assert(uuid as NSUUID, isDecodedAs: uuid as NSUUID)
try assert(data, isDecodedAs: uuid as NSUUID)
}
func testNSUUIDFromDatabaseValueFailure() {
let databaseValue_Null = DatabaseValue.null
let databaseValue_Int64 = Int64(1).databaseValue
let databaseValue_Double = Double(100000.1).databaseValue
let databaseValue_String = "56e7d8d3-e9e4-48b6-968e-8d102833af00".databaseValue
let databaseValue_badBlob = "bar".data(using: .utf8)!.databaseValue
XCTAssertNil(NSUUID.fromDatabaseValue(databaseValue_Null))
XCTAssertNil(NSUUID.fromDatabaseValue(databaseValue_Int64))
XCTAssertNil(NSUUID.fromDatabaseValue(databaseValue_Double))
XCTAssertNil(NSUUID.fromDatabaseValue(databaseValue_String))
XCTAssertNil(NSUUID.fromDatabaseValue(databaseValue_badBlob))
func testSuccess() throws {
try assertRoundTrip(UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!)
try assertRoundTrip(UUID())
try assert("abcdefghijklmnop".data(using: .utf8)!, isDecodedAs: NSUUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70"))
}
func testFailure() throws {
try assert(nil, isDecodedAs: nil)
try assert(DatabaseValue.null, isDecodedAs: nil)
try assert(1, isDecodedAs: nil)
try assert(100000.1, isDecodedAs: nil)
try assert("56e7d8d3e9e448b6968e8d102833af0", isDecodedAs: nil)
try assert("56e7d8d3-e9e4-48b6-968e-8d102833af0!", isDecodedAs: nil)
try assert("foo", isDecodedAs: nil)
try assert("bar".data(using: .utf8)!, isDecodedAs: nil)
try assert("abcdefghijklmno".data(using: .utf8)!, isDecodedAs: nil)
try assert("abcdefghijklmnopq".data(using: .utf8)!, isDecodedAs: nil)
}
}
+38 -33
View File
@@ -1,4 +1,5 @@
import XCTest
import Foundation
#if GRDBCIPHER
import GRDBCipher
#elseif GRDBCUSTOMSQLITE
@@ -8,47 +9,51 @@ import XCTest
#endif
class FoundationUUIDTests: GRDBTestCase {
func testUUIDDatabaseRoundTrip() throws {
let dbQueue = try makeDatabaseQueue()
func roundTrip(_ value: UUID) throws -> Bool {
guard let back = try dbQueue.inDatabase({ try UUID.fetchOne($0, "SELECT ?", arguments: [value]) }) else {
XCTFail()
return false
private func assert(_ value: DatabaseValueConvertible?, isDecodedAs expectedUUID: UUID?) throws {
try makeDatabaseQueue().read { db in
if let expectedUUID = expectedUUID {
let decodedUUID = try UUID.fetchOne(db, "SELECT ?", arguments: [value])
XCTAssertEqual(decodedUUID, expectedUUID)
} else if value == nil {
let decodedUUID = try Optional<UUID>.fetchAll(db, "SELECT NULL")[0]
XCTAssertNil(decodedUUID)
}
return back == value
}
XCTAssertTrue(try roundTrip(UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!))
XCTAssertTrue(try roundTrip(UUID()))
let decodedUUID = UUID.fromDatabaseValue(value?.databaseValue ?? .null)
XCTAssertEqual(decodedUUID, expectedUUID)
}
func testUUIDDatabaseValueRoundTrip() {
func roundTrip(_ value: UUID) -> Bool {
let dbValue = value.databaseValue
guard let back = UUID.fromDatabaseValue(dbValue) else {
XCTFail("Failed to convert from DatabaseValue to UUID")
return false
}
return back == value
private func assertRoundTrip(_ uuid: UUID) throws {
let string = uuid.uuidString
var uuid_t = uuid.uuid
let data = withUnsafeBytes(of: &uuid_t) {
Data(bytes: $0.baseAddress!, count: $0.count)
}
XCTAssertTrue(roundTrip(UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!))
XCTAssertTrue(roundTrip(UUID()))
try assert(string, isDecodedAs: uuid)
try assert(string.lowercased(), isDecodedAs: uuid)
try assert(string.uppercased(), isDecodedAs: uuid)
try assert(uuid, isDecodedAs: uuid)
try assert(uuid as NSUUID, isDecodedAs: uuid)
try assert(data, isDecodedAs: uuid)
}
func testUUIDFromDatabaseValueFailure() {
let databaseValue_Null = DatabaseValue.null
let databaseValue_Int64 = Int64(1).databaseValue
let databaseValue_Double = Double(100000.1).databaseValue
let databaseValue_String = "56e7d8d3-e9e4-48b6-968e-8d102833af00".databaseValue
let databaseValue_badBlob = "bar".data(using: .utf8)!.databaseValue
XCTAssertNil(UUID.fromDatabaseValue(databaseValue_Null))
XCTAssertNil(UUID.fromDatabaseValue(databaseValue_Int64))
XCTAssertNil(UUID.fromDatabaseValue(databaseValue_Double))
XCTAssertNil(UUID.fromDatabaseValue(databaseValue_String))
XCTAssertNil(UUID.fromDatabaseValue(databaseValue_badBlob))
func testSuccess() throws {
try assertRoundTrip(UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!)
try assertRoundTrip(UUID())
try assert("abcdefghijklmnop".data(using: .utf8)!, isDecodedAs: UUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70"))
}
func testFailure() throws {
try assert(nil, isDecodedAs: nil)
try assert(DatabaseValue.null, isDecodedAs: nil)
try assert(1, isDecodedAs: nil)
try assert(100000.1, isDecodedAs: nil)
try assert("56e7d8d3e9e448b6968e8d102833af0", isDecodedAs: nil)
try assert("56e7d8d3-e9e4-48b6-968e-8d102833af0!", isDecodedAs: nil)
try assert("foo", isDecodedAs: nil)
try assert("bar".data(using: .utf8)!, isDecodedAs: nil)
try assert("abcdefghijklmno".data(using: .utf8)!, isDecodedAs: nil)
try assert("abcdefghijklmnopq".data(using: .utf8)!, isDecodedAs: nil)
}
}