Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expose joining methods on both requests and associations #539

Merged
merged 13 commits into from
May 30, 2019

Conversation

groue
Copy link
Owner

@groue groue commented May 29, 2019

This PR is one more stone added on the empowering of constrained extensions to the DerivableRequest protocol. Such extensions are, in spirit, very close to Active Record Scopes. They allow to extend the query language, and reuse code between requests and associations for filtering, ordering, etc.

Joining methods are now available for the DerivableRequest protocol. For example:

/// Extends the query language for both Book requests and associations:
extension DerivableRequest where RowDecoder == Book {
    /// Filter books whose author is from the given country
    func filter(countryCode: String) -> Self {
        // Require that books can be joined to an author from this country:
        return joining(required: Book.author.filter(Column("countryCode") == countryCode)
    }
}

// Usage

// French books
let frenchBooks: [Book] = try Book.all()
    .filter(countryCode: "FR")
    .fetchAll(db)

// All libraries that contain Italian books
let libraries: [Library] = try Library
    .having(Library.books.filter(countryCode: "IT").isEmpty == false)
    .fetchAll(db)

Extensions to DerivableRequest are designed to be easily composable. Particularly, joining methods "hidden" in such extensions can freely be composed with other uses of associations, thanks to #422:

// French books with their author
struct BookInfo: Decodable, FetchableRecord {
    var book: Book
    var author: Author
}
let request = try Book.all()
    .filter(countryCode: "FR")
    .including(required: Book.author)
let bookInfos = try BookInfo.fetchAll(db, request)

@groue groue force-pushed the dev/JoinableRequest branch from 402102e to 35e1aeb Compare May 29, 2019 12:07
@groue groue added this to the GRDB 4.1.0 milestone May 29, 2019
@groue groue merged commit ff45864 into development May 30, 2019
@groue groue deleted the dev/JoinableRequest branch May 30, 2019 06:50
@groue groue changed the title Expose joining methods of both requests and associations Expose joining methods on both requests and associations Jun 13, 2019
@groue groue mentioned this pull request Jun 14, 2019
10 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant