Middle+
func (r *OrderRepository) GetActiveOrderIDs(ctx context.Context, offset, limit int) ([]uint32, error) { var ( res []uint32 args []interface{} ) query := `SELECT id FROM "order" WHERE is_terminated = false LIMIT $1 OFFSET $2;` args = append(args, limit, offset) rows, err := r.slave.Query(ctx, query, args...) if err != nil { return nil, err } for rows.Next() { var orderID uint32 if err = rows.Scan(&orderID); err != nil { return nil, err } res = append(res, orderID) } return res, nil }
sobes.tech AI
Answer from AI
This method in Go implements a database query to retrieve active order IDs with pagination (offset and limit).
The code correctly uses a prepared statement with parameters, which prevents SQL injection.
However, there are some recommendations for improvement:
- It is advisable to close
rowsafter use to avoid resource leaks:
rows, err := r.slave.Query(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
-
You can use
rows.Err()after the loop to check for iteration errors. -
LIMIT and OFFSET parameters usually follow the order LIMIT, OFFSET, but in the query, they are specified as LIMIT $1 OFFSET $2, which corresponds to passing limit, offset — this is correct.
-
If a large amount of data is expected, consider using cursors or streaming processing.
Example with added closing of rows and error checking:
rows, err := r.slave.Query(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var orderID uint32
if err = rows.Scan(&orderID); err != nil {
return nil, err
}
res = append(res, orderID)
}
if err = rows.Err(); err != nil {
return nil, err
}
return res, nil