go-jet / jet

Type safe SQL builder with code generation and automatic query result data mapping
Apache License 2.0
2.52k stars 118 forks source link

Scan into a map. #279

Closed CmpHDL closed 8 months ago

CmpHDL commented 11 months ago

Occasionally, I'll use a 3rd party API call that returns a slice of X. Usually I'll double store these in our database so users can soft-delete etc. Thus to filter, I have to fetch all X from the 3rd party API then iterate through and check if its in the slice returned from our database.

It is possible to instead scan into a map so as I iterate, rather than iterate through the entire slice, I can just match the primary key to the struct?

Ideally we could scan into some sort of map[PrimaryKeyType]dest instead of []dest .

[Right now I technically do the opposite, converting the 3rd party api into a map by looping, then loop through db records matching the primary key and creating a new slice. But I can see this being useful for other things involving mapping in general.]

go-jet commented 11 months ago

This should be already possible using Rows method. For instance:

stmt := SELECT(
    Rental.AllColumns,
).FROM(
    Rental,
)

rows, err := stmt.Rows(context.Background(), db)

var result = make(map[int32]model.Rental)

for rows.Next() {
    var rental model.Rental

    err := rows.Scan(&rental)

    result[rental.RentalID] = rental
}