diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index d21cf4f71..1470225b2 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -39,6 +39,7 @@ GRDB Associations - [Aggregate Operations] - [Isolation of Multiple Aggregates] - [DerivableRequest Protocol] +- **[FAQ]** - [Known Issues] @@ -2468,3 +2469,4 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [persistence methods]: ../README.md#persistence-methods [database observation tools]: ../README.md#database-changes-observation [ValueObservation]: ../README.md#valueobservation +[FAQ]: ../README.md#faq-associations diff --git a/README.md b/README.md index 76b27c4c5..b155ecf87 100644 --- a/README.md +++ b/README.md @@ -262,6 +262,8 @@ Documentation **GRDB runs on top of SQLite**: you should get familiar with the [SQLite FAQ](http://www.sqlite.org/faq.html). For general and detailed information, jump to the [SQLite Documentation](http://www.sqlite.org/docs.html). +#### [FAQ] + #### Reference - [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) @@ -313,7 +315,7 @@ Documentation - :blue_book: [Unexpected SQLite with Swift](https://hackernoon.com/unexpected-sqlite-with-swift-ddc6343bcbfc) -**[FAQ](#faq)** +**[FAQ]** **[Sample Code](#sample-code)** @@ -7278,17 +7280,36 @@ try writer.asyncWriteWithoutTransaction { db in FAQ === +**[FAQ: Opening Connections](#faq-opening-connections)** + - [How do I create a database in my application?](#how-do-i-create-a-database-in-my-application) - [How do I open a database stored as a resource of my application?](#how-do-i-open-a-database-stored-as-a-resource-of-my-application) - [How do I close a database connection?](#how-do-i-close-a-database-connection) + +**[FAQ: SQL](#faq-sql)** + - [How do I print a request as SQL?](#how-do-i-print-a-request-as-sql) + +**[FAQ: General](#faq-general)** + - [How do I monitor the duration of database statements execution?](#how-do-i-monitor-the-duration-of-database-statements-execution) +- [What Are Experimental Features?](#what-are-experimental-features) + +**[FAQ: Associations](#faq-associations)** + +- [How to I filter records and only keep those that are associated to another record?](#how-to-i-filter-records-and-only-keep-those-that-are-associated-to-another-record) +- [How to I filter records and only keep those that are NOT associated to another record?](#how-to-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record) +- [How to I select only one column of an associated record?](#how-to-i-select-only-one-column-of-an-associated-record) + +**[FAQ: Errors](#faq-errors)** + - [Generic parameter 'T' could not be inferred](#generic-parameter-t-could-not-be-inferred) - [SQLite error 10 "disk I/O error", SQLite error 23 "not authorized"](#sqlite-error-10-disk-io-error-sqlite-error-23-not-authorized) - [SQLite error 21 "wrong number of statement arguments" with LIKE queries](#sqlite-error-21-wrong-number-of-statement-arguments-with-like-queries) -- [What Are Experimental Features?](#what-are-experimental-features) +## FAQ: Opening Connections + ### How do I create a database in my application? This question assumes that your application has to create a new database from scratch. If your app has to open an existing database that is embedded inside your application as a resource, see [How do I open a database stored as a resource of my application?](#how-do-i-open-a-database-stored-as-a-resource-of-my-application) instead. @@ -7337,6 +7358,8 @@ Database connections are managed by [database queues](#database-queues) and [poo Database accesses that run in background threads postpone the closing of connections. +## FAQ: SQL + ### How do I print a request as SQL? When you want to debug a request that does not deliver the expected results, you may want to print the SQL that is actually executed. @@ -7382,6 +7405,8 @@ db.trace { event in > :point_up: **Note**: the generated SQL may change between GRDB releases, without notice: don't have your application rely on any specific SQL output. +## FAQ: General + ### How do I monitor the duration of database statements execution? Use the `trace(options:_:)` method, with the `.profile` option: @@ -7408,6 +7433,133 @@ try dbQueue.read { db in ``` +## FAQ: Associations + +### How to I filter records and only keep those that are associated to another record? + +Let's say you have two record types, `Book` and `Author`, and you want to only fetch books that have an author, and discard anonymous books. + +We start by defining the association between books and authors: + +```swift +struct Book: TableRecord { + ... + let author = belongsTo(Author.self) +} +struct Author: TableRecord { + ... +} +``` + +And then we can write our request and only fetch books that have an author, discarding anonymous ones: + +```swift +let books: [Book] = try dbQueue.read { db in + // SELECT book.* FROM book + // JOIN author ON author.id = book.authorID + let request = Book.joining(required: Book.author) + return try request.fetchAll(db) +} +``` + +Note how this request does not use the `filter` method. Indeed, we don't have any condition to express on book columns. Instead, we just need to express that it is "required that a book can be joined to its author". + +See [How to I filter records and only keep those that are NOT associated to another record?](#how-to-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record) below for the opposite question. + + +### How to I filter records and only keep those that are NOT associated to another record? + +Let's say you have two record types, `Book` and `Author`, and you want to only fetch anonymous books that do not have any author. + +We start by defining the association between books and authors: + +```swift +struct Book: TableRecord { + ... + let author = belongsTo(Author.self) +} +struct Author: TableRecord { + ... +} +``` + +And then we can write our request and only fetch anonymous books that have an author: + +```swift +let books: [Book] = try dbQueue.read { db in + // SELECT book.* FROM book + // LEFT JOIN author ON author.id = book.authorID + // WHERE author.rowid IS NULL + let authorAlias = TableAlias() + let request = Book + .joining(optional: Book.author.aliased(authorAlias)) + .filter(authorAlias[Column.rowID] == nil) + return try request.fetchAll(db) +} +``` + +This request uses a TableAlias in order to be able to filter on the eventual associated author. We make sure that their `Column.rowID` (another name for their primary key) is nil, which is another way to say it does not exist: the book has no author. + +See [How to I filter records and only keep those that are associated to another record?](#how-to-i-filter-records-and-only-keep-those-that-are-associated-to-another-record) above for the opposite question. + + +### How to I select only one column of an associated record? + +Let's say you have two record types, `Book` and `Author`, and you want to fetch all books with their author name, but not the full author records: + +We start by defining the association between books and authors: + +```swift +struct Book: Decodable, TableRecord { + ... + let author = belongsTo(Author.self) +} +struct Author: TableRecord { + ... + enum Columns { + static let name = Column(CodingKeys.name) + } +} +``` + +And then we can write our request and the ad-hoc record that decodes it: + +```swift +struct BookInfo: Decodable, FetchableRecord { + var book: Book + var authorName: String? // nil when the book is anonymous + + static func all() -> QueryInterfaceRequest { + // SELECT book.*, author.name AS authorName + // FROM book + // LEFT JOIN author ON author.id = book.authorID + let authorAlias = TableAlias() + let authorName = authorAlias[Author.Columns.name].forKey(CodingKeys.authorName) + return Book + .annotated(with: authorName) + .joining(optional: Book.author.aliased(authorAlias)) + .asRequest(of: BookInfo.self) + } +} + +let bookInfos: [BookInfo] = try dbQueue.read { db in + BookInfo.all().fetchAll(db) +} +``` + +By using a TableAlias, you can refer to an author column from a request of books. + +By defining the request as a static method of BookInfo, you have access to the private `CodingKeys.authorName`, and a compiler-checked SQL column name. + +By using the `annotated(with:)` method, you append the author name to the top-level selection that can be decoded by the ad-hoc record. + +By using the `joining()` method, you make sure no author column is selected, but the one declared in `annotated(with:)`. + +By using `asRequest(of:)`, you enhance the type-safety of your request. + + +## FAQ: Errors + ### Generic parameter 'T' could not be inferred You may get this error when using the `read` and `write` methods of database queues and pools: @@ -7595,3 +7747,4 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv [Combine]: https://developer.apple.com/documentation/combine [Demo Application]: Documentation/DemoApps/GRDBDemoiOS/README.md [Sharing a Database]: Documentation/SharingADatabase.md +[FAQ]: #faq