jschaf / pggen

Generate type-safe Go for any Postgres query. If Postgres can run the query, pggen can generate code for it.
MIT License
281 stars 26 forks source link

Proposal: Accessor methods for row structs #57

Closed leg100 closed 2 years ago

leg100 commented 2 years ago

Might it be a good idea to provide accessor methods on the row structs, specifically "getters"? Here's an example of how they help abstract across different row structs with the same fields.

type FindAuthorsRow struct {
    AuthorID  int32   `json:"author_id"`
    FirstName string  `json:"first_name"`
    LastName  string  `json:"last_name"`
    Suffix    *string `json:"suffix"`
}

type FindAuthorByIDRow struct {
    AuthorID  int32   `json:"author_id"`
    FirstName string  `json:"first_name"`
    LastName  string  `json:"last_name"`
    Suffix    *string `json:"suffix"`
}

type Name interface {
    GetFirstName() string
    GetLastName() string
}

func handleName(name Name) {
    first := name.GetFirstName()
    last := name.GetLastName()
    ...
}

authors, _ := q.FindAuthors(context.Background(), "john")
authorByID, _ := q.FindAuthorByID(context.Background(), 123)

for _, author := range authors {
    handleName(author)
}
handleName(authorByID)
leg100 commented 2 years ago

I've just seen an identical issue for sqlc, closed with a fairly reasonable objection: a generated accessor method may conflict with a field with the same name.

jschaf commented 2 years ago

I've just seen an https://github.com/kyleconroy/sqlc/pull/387, closed with a fairly reasonable objection: a generated accessor method may conflict with a field with the same name.

Yea, that's a pretty good reason not to do it. I'll close this in favor of #44 (and a dupe #58) which solves this issue directly.