From 67ec70a117202e371db272aac04bb33810092c64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 16 May 2019 22:00:30 +0200 Subject: [PATCH] Row prefetch subscript --- GRDB/Core/Row.swift | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 523e13e55..9d96b960d 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -542,6 +542,46 @@ extension Row { } return Record(row: scopedRow) } + + /// Returns the records encoded in the given prefetched rows. + /// + /// struct Author: FetchableRecord, TableRecord { + /// static let books = hasMany(Book.self) + /// ... + /// } + /// struct Book: FetchableRecord, TableRecord { + /// ... + /// } + /// + /// struct AuthorInfo { + /// var author: Author + /// var books: [Book] + /// + /// init(row: Row) { + /// author = Author(row: row) + /// books = row["books"] // <--- + /// } + /// } + /// + /// try dbQueue.read { db in + /// // Fetch authors along with their books: + /// let request = Author.including(all: Author.books) + /// let authorInfos = try AuthorInfo.fetchAll(db, request) + /// + /// for authorInfo in authorInfos { + /// print("\(authorInfo.author.name) wrote:") + /// for book in authorInfo.books { + /// print("- \(book.title)") + /// } + /// } + /// } + public subscript(_ key: String) -> [Record] { + guard let rows = prefetches[key] else { + // Programmer error + fatalError("no such prefetched rows: \(key)") + } + return rows.map(Record.init(row:)) + } } extension Row {