Skip to content

[FEATURE] Scanning multiple rows to map #963

@johnnybubonic

Description

@johnnybubonic

.Select() should support scanning into a map IF AND ONLY IF the following conditions are true (otherwise return error):

  • the table has a primary key
  • the map's key type is scannable for the table's primary key
  • the map's value type is StructScan()-compat with the rows

Thus, a table like:

CREATE TABLE `example_tbl` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `val1` varchar(16),
  `val2` int,
  PRIMARY KEY (`id`)
);

and code like:

package main

// imports etc.

type ExampleRow struct {
	ID     uint   `db:"id"`
	Value1 string `db:"val1"`
	Value2 int    `db:"val2"`
}

func main() {

	var err error
	var db *sqlx.DB
	var rows map[uint]*ExampleRow

	// db setup etc.
	defer db.Close()

	rows = make(map[uint]*ExampleRow)
	if err = db.Select(&rows, "SELECT * FROM example_tbl"); err != nil {
		log.Panicln(err)
	}

	/*
		rows would now be keyed on the `id` column's values as it's the PK,
		and each value would be a StructScan of an ExampleRow.
	*/
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions