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

Query Interface: set the selection and the fetched type in a single method call #401

Merged
merged 6 commits into from
Aug 19, 2018

Conversation

groue
Copy link
Owner

@groue groue commented Aug 19, 2018

This PR introduces the new select(..., as:...) method:

// new
let request = Player.select(max(Column("score")), as: Int.self)

This new method does not bring any new functionality. It is 100% equivalent to the already available select(...).asRequest(of:...):

// old way to do it
let request = Player
    .select(max(Column("score")))
    .asRequest(of: Int.self)

The goal of this PR is to help building apis that return requests (instead of returning fetched values). For example:

struct Player: Codable, FetchableRecord, PersistableRecord {
    var uuid: UUID
    var name: String
    var score: Int
    
    private enum CodingKeys: String, CodingKey, ColumnExpression {
        case uuid, name, score
    }
    
    static var maximumScore: QueryInterfaceRequest<Int> {
        // new
        return select(max(CodingKeys.score)), as: Int.self)
    }
    
    static func uuid(forName name: String) -> QueryInterfaceRequest<UUID> {
        // new
        return filter(CodingKeys.name == name)
            .select(CodingKeys.uuid, as: UUID.self)
    }
}

// Fetch
dbQueue.read { db in
    let maximumScore: Int? = try Player.maximumScore.fetchOne(db)
    let uuid: UUID? = try Player.uuid(forName: "Arthur").fetchOne(db)
}

// Observe with RxGRDB
Player.maximumScore.rx
    .fetchOne(in: dbQueue)
    .subscribe(onNext: { maximumScore: Int? in
        print("maximum score has changed")
    })

groue added 5 commits August 19, 2018 12:25
Record.select(..., as: Value.self) is equivalent to Record.select(...).asRequest(of: Value.self).

It somewhat improves the readability of some requests:

Player.select(max(Column("score")), as: Int.self)
@groue groue merged commit d45afb9 into development Aug 19, 2018
@groue groue deleted the feature/selectAs branch August 19, 2018 13:54
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