MapsQuery
Use db.MapsQuery to read database rows as dynamic map values from a prepared db.Query.
Use db.MapsQuery when you already have a db.Query value and want the result as dynamic map[string]any rows.
It is the query-object version of db.Maps.
events, err := db.MapsQuery(ctx, conn, q)
if err != nil {
return nil, err
}Function
func MapsQuery(ctx context.Context, c db.Querier, q db.Query) ([]map[string]any, error)MapsQuery accepts:
- a
context.Context - a connection or query-capable value
- a
db.Query
It returns:
[]map[string]any, errorEach map represents one returned row.
When to Use MapsQuery
Use db.MapsQuery when:
- you already created a
db.Query - the result shape is dynamic
- query creation and execution are separate steps
- the query was created by
db.Rawordb.Dialect - you are building reports, exports, admin tools, or generic views
- you do not want to define a struct for the result
For direct query strings, use db.Maps.
Create a Query Object
Create a db.Query using db.Raw.
For MySQL and Scylla, use ? placeholders.
const selectEventsQuery = `
SELECT *
FROM events
ORDER BY created_at DESC
LIMIT ?
`q, err := db.Raw(selectEventsQuery, 10)
if err != nil {
return nil, err
}For PostgreSQL, the query uses numbered placeholders.
const selectEventsQuery = `
SELECT *
FROM events
ORDER BY created_at DESC
LIMIT $1
`The Go code stays the same:
q, err := db.Raw(selectEventsQuery, 10)
if err != nil {
return nil, err
}Execute the Query Object
Pass the query object into db.MapsQuery.
events, err := db.MapsQuery(ctx, conn, q)
if err != nil {
return nil, err
}
return events, nilComplete Query Example
This example creates a db.Query and reads event rows as dynamic maps.
package main
import (
"context"
"github.com/netlifeguru/db"
)
const selectEventsQuery = `
SELECT *
FROM events
ORDER BY created_at DESC
LIMIT ?
`
func ListEventsQuery(ctx context.Context, conn db.Conn, limit int) ([]map[string]any, error) {
q, err := db.Raw(selectEventsQuery, limit)
if err != nil {
return nil, err
}
return db.MapsQuery(ctx, conn, q)
}Complete Usage Example
This example connects to the database, executes the query-object helper, and prints map values.
package main
import (
"context"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
"github.com/joho/godotenv"
)
func main() {
err := godotenv.Load()
if err != nil {
log.Println(".env file not found, I'm using system env variables")
}
conn, err := connectDB()
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
events, err := ListEventsQuery(ctx, conn, 10)
if err != nil {
log.Fatal(err)
}
for _, event := range events {
fmt.Printf(
"ID: %v | Type: %v | Payload: %v | Created: %v\n",
event["id"],
event["type"],
event["payload"],
event["created_at"],
)
}
}Returned Row Shape
Each returned row is represented as map[string]any.
map[string]any{
"id": int64(1),
"type": "user.created",
"payload": `{"name":"John Doe"}`,
"created_at": time.Now(),
}The exact Go value types depend on the database driver and returned column types.
SQL Aliases
Map keys are based on returned column names.
Use aliases when selecting computed values or joining tables.
SELECT
u.id AS user_id,
u.email AS user_email,
COUNT(o.id) AS order_count
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
GROUP BY u.id, u.emailThe resulting map will contain the alias names:
map[string]any{
"user_id": int64(1),
"user_email": "john@example.com",
"order_count": int64(3),
}Typed Access
For typed access, convert a returned map to mapper.Row.
row := mapper.Row(events[0])
eventType, ok := row.String("type")
if !ok {
return errors.New("invalid event type")
}Or use standalone mapper converters:
eventType, ok := mapper.AsString(events[0]["type"])
if !ok {
return errors.New("invalid event type")
}Use maps directly for generic output.
Use typed access when values are required for business logic.
Empty Results
If the query returns no rows, db.MapsQuery returns an empty slice.
events, err := db.MapsQuery(ctx, conn, q)
if err != nil {
return nil, err
}
fmt.Println(len(events)) // 0An empty result is not treated as an error.
Raw Query Validation
db.Raw returns an error when the query string is empty.
q, err := db.Raw("")
if err != nil {
return nil, err
}This prevents empty query objects from being executed accidentally.
Query Objects From Dialect SQL
MapsQuery is often used together with db.Dialect.
q, err := db.Dialect(conn, queries.EventsReport, 10)
if err != nil {
return nil, err
}
return db.MapsQuery(ctx, conn, q)For direct dialect usage, you can also use db.MapsDialect.
events, err := db.MapsDialect(ctx, conn, queries.EventsReport, 10)Related Helpers
Use db.Maps when you want to pass the query string directly.
events, err := db.Maps(ctx, conn, selectEventsQuery, 10)Use db.ListQuery when the query object returns multiple typed rows.
users, err := db.ListQuery[User](ctx, conn, q)Use db.GetQuery when the query object returns zero or one typed row.
user, found, err := db.GetQuery[User](ctx, conn, q)Use db.ValueQuery when the query object returns one scalar value.
total, found, err := db.ValueQuery[int64](ctx, conn, q)Related Examples
Standalone examples are available in the examples repository: