From 17e8df2d25a7fbc3a86eca5818734df6aa98104a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 5 May 2019 21:09:23 +0200 Subject: [PATCH] Tests for consumption of prefetched rows into Decodable records --- .../FetchableRecord+QueryInterface.swift | 82 +++++---- GRDB/QueryInterface/Row+QueryInterface.swift | 8 +- GRDB/Record/FetchableRecord+Decodable.swift | 159 ++++++++++++++++-- .../AssociationPrefetchingTests.swift | 50 +++++- 4 files changed, 244 insertions(+), 55 deletions(-) diff --git a/GRDB/QueryInterface/FetchableRecord+QueryInterface.swift b/GRDB/QueryInterface/FetchableRecord+QueryInterface.swift index 049a0d0d8..cdc2db169 100644 --- a/GRDB/QueryInterface/FetchableRecord+QueryInterface.swift +++ b/GRDB/QueryInterface/FetchableRecord+QueryInterface.swift @@ -1,3 +1,31 @@ +extension QueryInterfaceRequest where RowDecoder: FetchableRecord { + /// An array of fetched records. + /// + /// let request: QueryInterfaceRequest = ... + /// let players = try request.fetchAll(db) // [Player] + /// + /// - parameter db: A database connection. + /// - returns: An array of records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + @inlinable // TODO: should not be inlinable + public func fetchAll(_ db: Database) throws -> [RowDecoder] { + return try RowDecoder.fetchAll(db, self) + } + + /// The first fetched record. + /// + /// let request: QueryInterfaceRequest = ... + /// let player = try request.fetchOne(db) // Player? + /// + /// - parameter db: A database connection. + /// - returns: An optional record. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + @inlinable // TODO: should not be inlinable + public func fetchOne(_ db: Database) throws -> RowDecoder? { + return try RowDecoder.fetchOne(db, self) + } +} + extension FetchableRecord { // MARK: Fetching From QueryInterfaceRequest @@ -12,11 +40,17 @@ extension FetchableRecord { /// - sql: a FetchRequest. /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - @inlinable + @inlinable // TODO: should not be inlinable public static func fetchAll(_ db: Database, _ request: QueryInterfaceRequest) throws -> [Self] { - // TODO: prefetch if needed let (statement, adapter) = try request.prepare(db, forSingleResult: false) - return try fetchAll(statement, adapter: adapter) + let associations = request.prefetchedAssociations + if associations.isEmpty { + return try fetchAll(statement, adapter: adapter) + } else { + let rows = try Row.fetchAll(statement, adapter: adapter) + try Row.prefetch(db, associations: associations, in: rows) + return rows.map(Self.init(row:)) + } } /// Returns a single record fetched from a query interface request. @@ -29,38 +63,18 @@ extension FetchableRecord { /// - sql: a FetchRequest. /// - returns: An optional record. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - @inlinable + @inlinable // TODO: should not be inlinable public static func fetchOne(_ db: Database, _ request: QueryInterfaceRequest) throws -> Self? { - // TODO: prefetch if needed let (statement, adapter) = try request.prepare(db, forSingleResult: true) - return try fetchOne(statement, adapter: adapter) - } -} - -extension QueryInterfaceRequest where RowDecoder: FetchableRecord { - /// An array of fetched records. - /// - /// let request: QueryInterfaceRequest = ... - /// let players = try request.fetchAll(db) // [Player] - /// - /// - parameter db: A database connection. - /// - returns: An array of records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - @inlinable - public func fetchAll(_ db: Database) throws -> [RowDecoder] { - return try RowDecoder.fetchAll(db, self) - } - - /// The first fetched record. - /// - /// let request: QueryInterfaceRequest = ... - /// let player = try request.fetchOne(db) // Player? - /// - /// - parameter db: A database connection. - /// - returns: An optional record. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - @inlinable - public func fetchOne(_ db: Database) throws -> RowDecoder? { - return try RowDecoder.fetchOne(db, self) + let associations = request.prefetchedAssociations + if associations.isEmpty { + return try fetchOne(statement, adapter: adapter) + } else { + guard let row = try Row.fetchOne(statement, adapter: adapter) else { + return nil + } + try Row.prefetch(db, associations: associations, in: [row]) + return Self.init(row: row) + } } } diff --git a/GRDB/QueryInterface/Row+QueryInterface.swift b/GRDB/QueryInterface/Row+QueryInterface.swift index 2312ba6c6..cc7fef7cc 100644 --- a/GRDB/QueryInterface/Row+QueryInterface.swift +++ b/GRDB/QueryInterface/Row+QueryInterface.swift @@ -12,7 +12,7 @@ extension QueryInterfaceRequest where RowDecoder == Row { /// - parameter db: A database connection. /// - returns: An array of fetched rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - @inlinable + @inlinable // TODO: should not be inlinable public func fetchAll(_ db: Database) throws -> [Row] { return try Row.fetchAll(db, self) } @@ -25,7 +25,7 @@ extension QueryInterfaceRequest where RowDecoder == Row { /// - parameter db: A database connection. /// - returns: An optional row. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - @inlinable + @inlinable // TODO: should not be inlinable public func fetchOne(_ db: Database) throws -> Row? { return try Row.fetchOne(db, self) } @@ -45,7 +45,7 @@ extension Row { /// - request: A FetchRequest. /// - returns: An array of rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - @inlinable + @inlinable // TODO: should not be inlinable public static func fetchAll(_ db: Database, _ request: QueryInterfaceRequest) throws -> [Row] { let (statement, adapter) = try request.prepare(db, forSingleResult: false) let rows = try fetchAll(statement, adapter: adapter) @@ -67,7 +67,7 @@ extension Row { /// - request: A FetchRequest. /// - returns: An optional row. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - @inlinable + @inlinable // TODO: should not be inlinable public static func fetchOne(_ db: Database, _ request: QueryInterfaceRequest) throws -> Row? { let (statement, adapter) = try request.prepare(db, forSingleResult: true) guard let row = try fetchOne(statement, adapter: adapter) else { diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 2c22a88fa..6b951a065 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -17,10 +17,10 @@ extension FetchableRecord where Self: Decodable { // MARK: - RowDecoder /// The decoder that decodes a record from a database row -private struct RowDecoder: Decoder { +private struct RowDecoder: Decoder { var row: Row var codingPath: [CodingKey] - var userInfo: [CodingUserInfoKey: Any] { return Record.databaseDecodingUserInfo } + var userInfo: [CodingUserInfoKey: Any] { return R.databaseDecodingUserInfo } func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer { return KeyedDecodingContainer(KeyedContainer(decoder: self)) @@ -42,7 +42,7 @@ private struct RowDecoder: Decoder { } // TODO: test // See DatabaseValueConversionErrorTests.testDecodableFetchableRecord2 - return ColumnDecoder(row: row, columnIndex: index, codingPath: codingPath) + return ColumnDecoder(row: row, columnIndex: index, codingPath: codingPath) } struct KeyedContainer: KeyedDecodingContainerProtocol { @@ -55,9 +55,10 @@ private struct RowDecoder: Decoder { var allKeys: [Key] { let row = decoder.row - let columnNames = Set(row.columnNames) - let scopeNames = Set(row.scopesTree.names) - return columnNames.union(scopeNames).compactMap { Key(stringValue: $0) } + return Set(row.columnNames) + .union(Set(row.scopesTree.names)) + .union(Set(row.prefetchTree.keys)) + .compactMap { Key(stringValue: $0) } } func contains(_ key: Key) -> Bool { @@ -94,7 +95,7 @@ private struct RowDecoder: Decoder { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. if type == Date.self { - return Record.databaseDateDecodingStrategy.decodeIfPresent(fromRow: row, columnAtIndex: index) as! T? + return R.databaseDateDecodingStrategy.decodeIfPresent(fromRow: row, columnAtIndex: index) as! T? } else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type { return type.fastDecodeIfPresent(from: row, atUncheckedIndex: index) as! T? } else if let type = T.self as? DatabaseValueConvertible.Type { @@ -124,7 +125,7 @@ private struct RowDecoder: Decoder { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. if type == Date.self { - return Record.databaseDateDecodingStrategy.decode(fromRow: row, columnAtIndex: index) as! T + return R.databaseDateDecodingStrategy.decode(fromRow: row, columnAtIndex: index) as! T } else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type { return type.fastDecode(from: row, atUncheckedIndex: index) as! T } else if let type = T.self as? DatabaseValueConvertible.Type { @@ -139,6 +140,12 @@ private struct RowDecoder: Decoder { return try decode(type, fromRow: scopedRow, codingPath: codingPath + [key]) } + // Prefetched Rows? + if let prefetchedRows = row.prefetchTree[keyName] { + let decoder = PrefetchedRowsDecoder(rows: prefetchedRows, codingPath: codingPath) + return try T(from: decoder) + } + // Key is not a column, and not a scope. // // Should be throw an error? Well... The use case is the following: @@ -219,7 +226,7 @@ private struct RowDecoder: Decoder { // or unkeyed containers, because we're decoding a single // value here (string, int, double, data, null). If such an // error happens, we'll switch to JSON decoding. - let columnDecoder = ColumnDecoder( + let columnDecoder = ColumnDecoder( row: row, columnIndex: index, codingPath: codingPath + [key]) @@ -229,7 +236,7 @@ private struct RowDecoder: Decoder { guard let data = row.dataNoCopy(atIndex: index) else { fatalConversionError(to: T.self, from: row[index], conversionContext: ValueConversionContext(row).atColumn(index)) } - return try Record + return try R .databaseJSONDecoder(for: key.stringValue) .decode(type.self, from: data) } @@ -237,14 +244,140 @@ private struct RowDecoder: Decoder { } } +// MARK: - PrefetchedRowsDecoder + +private struct PrefetchedRowsDecoder: Decoder { + var rows: [Row] + var codingPath: [CodingKey] + var index: Int + var userInfo: [CodingUserInfoKey: Any] { return R.databaseDecodingUserInfo } + + init(rows: [Row], codingPath: [CodingKey]) { + self.rows = rows + self.codingPath = codingPath + self.index = 0 + } + + func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer where Key : CodingKey { + fatalError("keyed decoding from prefetched rows is not supported") + } + + func unkeyedContainer() throws -> UnkeyedDecodingContainer { + return self + } + + func singleValueContainer() throws -> SingleValueDecodingContainer { + fatalError("single value decoding from prefetched rows is not supported") + } +} + +extension PrefetchedRowsDecoder: UnkeyedDecodingContainer { + var count: Int? { + // TODO + fatalError("not implemented") + } + + var isAtEnd: Bool { + return index >= rows.endIndex + } + + var currentIndex: Int { + // TODO + fatalError("not implemented") + } + + mutating func decodeNil() throws -> Bool { + // TODO + fatalError("not implemented") + } + + mutating func decode(_ type: Bool.Type) throws -> Bool { + // TODO + fatalError("not implemented") + } + + mutating func decode(_ type: String.Type) throws -> String { + fatalError("not implemented") + } + + mutating func decode(_ type: Double.Type) throws -> Double { + fatalError("not implemented") + } + + mutating func decode(_ type: Float.Type) throws -> Float { + fatalError("not implemented") + } + + mutating func decode(_ type: Int.Type) throws -> Int { + fatalError("not implemented") + } + + mutating func decode(_ type: Int8.Type) throws -> Int8 { + fatalError("not implemented") + } + + mutating func decode(_ type: Int16.Type) throws -> Int16 { + fatalError("not implemented") + } + + mutating func decode(_ type: Int32.Type) throws -> Int32 { + fatalError("not implemented") + } + + mutating func decode(_ type: Int64.Type) throws -> Int64 { + fatalError("not implemented") + } + + mutating func decode(_ type: UInt.Type) throws -> UInt { + fatalError("not implemented") + } + + mutating func decode(_ type: UInt8.Type) throws -> UInt8 { + fatalError("not implemented") + } + + mutating func decode(_ type: UInt16.Type) throws -> UInt16 { + fatalError("not implemented") + } + + mutating func decode(_ type: UInt32.Type) throws -> UInt32 { + fatalError("not implemented") + } + + mutating func decode(_ type: UInt64.Type) throws -> UInt64 { + fatalError("not implemented") + } + + mutating func decode(_ type: T.Type) throws -> T where T : Decodable { + defer { index += 1 } + let decoder = RowDecoder(row: rows[index], codingPath: codingPath) + return try T(from: decoder) + } + + mutating func nestedContainer(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer where NestedKey : CodingKey { + // TODO + fatalError("not implemented") + } + + mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer { + // TODO + fatalError("not implemented") + } + + mutating func superDecoder() throws -> Decoder { + // TODO + fatalError("not implemented") + } +} + // MARK: - ColumnDecoder /// The decoder that decodes from a database column -private struct ColumnDecoder: Decoder { +private struct ColumnDecoder: Decoder { var row: Row var columnIndex: Int var codingPath: [CodingKey] - var userInfo: [CodingUserInfoKey: Any] { return Record.databaseDecodingUserInfo } + var userInfo: [CodingUserInfoKey: Any] { return R.databaseDecodingUserInfo } func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer { // We need to switch to JSON decoding @@ -285,7 +418,7 @@ extension ColumnDecoder: SingleValueDecodingContainer { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. if type == Date.self { - return Record.databaseDateDecodingStrategy.decode(fromRow: row, columnAtIndex: columnIndex) as! T + return R.databaseDateDecodingStrategy.decode(fromRow: row, columnAtIndex: columnIndex) as! T } else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type { return type.fastDecode(from: row, atUncheckedIndex: columnIndex) as! T } else if let type = T.self as? DatabaseValueConvertible.Type { diff --git a/Tests/GRDBTests/AssociationPrefetchingTests.swift b/Tests/GRDBTests/AssociationPrefetchingTests.swift index b0b716bed..c4451c3a4 100644 --- a/Tests/GRDBTests/AssociationPrefetchingTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingTests.swift @@ -5,20 +5,20 @@ import XCTest import GRDB #endif -private struct A: TableRecord, FetchableRecord, Decodable { +private struct A: TableRecord, FetchableRecord, Decodable, Equatable { var cola1: Int64 var cola2: String } -private struct B: TableRecord, FetchableRecord, Decodable { +private struct B: TableRecord, FetchableRecord, Decodable, Equatable { var colb1: Int64 var colb2: Int64 var colb3: String } -private struct C: TableRecord, FetchableRecord, Decodable { +private struct C: TableRecord, FetchableRecord, Decodable, Equatable { var colc1: Int64 var colc2: String } -private struct D: TableRecord, FetchableRecord, Decodable { +private struct D: TableRecord, FetchableRecord, Decodable, Equatable { var cold1: Int64 var cold2: Int64 var cold3: String @@ -144,6 +144,48 @@ class AssociationPrefetchingTests: GRDBTestCase { XCTAssertEqual(row.prefetchTree["bs"]![0], ["colb1": 4, "colb2": 1, "colb3": "b1", "grdb_colb2": 1]) // TODO: remove grdb_ column? XCTAssertEqual(row.prefetchTree["bs"]![1], ["colb1": 5, "colb2": 1, "colb3": "b2", "grdb_colb2": 1]) // TODO: remove grdb_ column? } + + // Record.fetchAll + do { + struct Record: FetchableRecord, Decodable, Equatable { + var a: A + var bs: [B] + } + + let records = try Record.fetchAll(db, request) + XCTAssertEqual(records, [ + Record( + a: A(row: ["cola1": 1, "cola2": "a1"]), + bs: [ + B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), + B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), + ]), + Record( + a: A(row: ["cola1": 2, "cola2": "a2"]), + bs: [ + B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), + ]), + Record( + a: A(row: ["cola1": 3, "cola2": "a3"]), + bs: []), + ]) + } + + // Record.fetchOne + do { + struct Record: FetchableRecord, Decodable, Equatable { + var a: A + var bs: [B] + } + + let record = try Record.fetchOne(db, request)! + XCTAssertEqual(record, Record( + a: A(row: ["cola1": 1, "cola2": "a1"]), + bs: [ + B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), + B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), + ])) + } } // Request with avoided prefetch