Gibheer
ee5acc6ded
This is a small library to build queries and put the result into the world. Currently it supports building the select clause and converting rows into a list of maps, so that it can be returned as a list.
36 lines
808 B
Go
36 lines
808 B
Go
package query
|
|
|
|
import (
|
|
"database/sql"
|
|
"fmt"
|
|
)
|
|
|
|
// RowsToMap converts a query result to a list of maps.
|
|
func RowsToMap(rows *sql.Rows) ([]map[string]interface{}, error) {
|
|
empty := []map[string]interface{}{}
|
|
res := []map[string]interface{}{}
|
|
cols, err := rows.Columns()
|
|
if err != nil {
|
|
return empty, fmt.Errorf("could not get columns: %v", err)
|
|
}
|
|
for rows.Next() {
|
|
if rows.Err() != nil {
|
|
return empty, fmt.Errorf("could not iterate rows: %v", err)
|
|
}
|
|
raw := make([]interface{}, len(cols))
|
|
for i, _ := range raw {
|
|
raw[i] = new(interface{})
|
|
}
|
|
if err := rows.Scan(raw...); err != nil {
|
|
return empty, fmt.Errorf("could not scan row: %v", err)
|
|
}
|
|
|
|
row := map[string]interface{}{}
|
|
for i, col := range cols {
|
|
row[col] = raw[i]
|
|
}
|
|
res = append(res, row)
|
|
}
|
|
return res, nil
|
|
}
|