Skip to content

feat: SelectKeyed scans rows into a map by column key#997

Open
sonnemusk wants to merge 1 commit into
jmoiron:masterfrom
sonnemusk:feat/select-keyed-map
Open

feat: SelectKeyed scans rows into a map by column key#997
sonnemusk wants to merge 1 commit into
jmoiron:masterfrom
sonnemusk:feat/select-keyed-map

Conversation

@sonnemusk

Copy link
Copy Markdown

Summary

Adds SelectKeyed / SelectKeyedContext (with DB / Tx / Stmt / Conn methods) so a query result can be loaded into a map[K]V keyed by a named column or db-tagged field.

var people map[string]Person
err := db.SelectKeyed(&people, "email", `SELECT first_name, last_name, email FROM person`)
// people["jmoiron@jmoiron.net"].FirstName == "Jason"

var byCode map[int]Place
err = db.SelectKeyed(&byCode, "telcode", `SELECT country, city, telcode FROM place`)

Rules

  • dest must be a non-nil *map[K]V
  • V must be a struct or *struct (StructScan-compatible); scannable map values are rejected
  • key is a column / field name resolved the same way as StructScan (db tags + NameMapper)
  • Map key type must be assignable or convertible from the key field type
  • Destination map is replaced with a fresh empty map before scanning (same idea as Select resetting slice length)
  • Duplicate keys: later row wins

Addresses #963 (map-by-primary-key style loading without requiring schema-level PK discovery).

Test plan

  • go test -run TestSelectKeyed
  • map[string]Person by email
  • map[string]*Person
  • map[int]Place by telcode
  • errors for missing key field, empty key, non-map dest

Add SelectKeyed / SelectKeyedContext (and DB/Tx/Stmt/Conn methods) so
callers can load query results into map[K]V keyed by a named column or
db-tagged field. Map values must be structs or *structs. Addresses jmoiron#963.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant