64 lines
1.3 KiB
Go
64 lines
1.3 KiB
Go
package db
|
|
|
|
import "database/sql"
|
|
|
|
func (c *Client) Select(query string, args ...any) ([]map[string]any, error) {
|
|
rows, err := c.query(query, args...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer func(rows *sql.Rows) {
|
|
_ = rows.Close()
|
|
}(rows)
|
|
|
|
cols, _ := rows.Columns()
|
|
var result []map[string]any
|
|
|
|
for rows.Next() {
|
|
columns := make([]any, len(cols))
|
|
columnPointers := make([]any, len(cols))
|
|
for i := range columns {
|
|
columnPointers[i] = &columns[i]
|
|
}
|
|
if err := rows.Scan(columnPointers...); err != nil {
|
|
return nil, err
|
|
}
|
|
rowMap := make(map[string]any)
|
|
for i, colName := range cols {
|
|
rowMap[colName] = columns[i]
|
|
}
|
|
result = append(result, rowMap)
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func (c *Client) SelectOne(query string, args ...any) (map[string]any, error) {
|
|
rows, err := c.query(query, args...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer func(rows *sql.Rows) {
|
|
_ = rows.Close()
|
|
}(rows)
|
|
|
|
if !rows.Next() {
|
|
return nil, sql.ErrNoRows
|
|
}
|
|
|
|
cols, _ := rows.Columns()
|
|
columns := make([]any, len(cols))
|
|
columnPointers := make([]any, len(cols))
|
|
for i := range columns {
|
|
columnPointers[i] = &columns[i]
|
|
}
|
|
if err := rows.Scan(columnPointers...); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
rowMap := make(map[string]any)
|
|
for i, colName := range cols {
|
|
rowMap[colName] = columns[i]
|
|
}
|
|
return rowMap, nil
|
|
}
|