Sobes.tech
Principal

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

In this Go code, a function is implemented to retrieve IDs of active orders with pagination (offset and limit). The code is generally correct, but there are a few points that can be improved:

  1. The order of LIMIT and OFFSET in SQL is usually LIMIT $1 OFFSET $2, which is followed here.
  2. It's better to use defer rows.Close() immediately after checking for errors to ensure the cursor is closed.
  3. You can use rows.Err() after the loop to check for iteration errors.

An improved version example:

func (r *OrderRepository) GetActiveOrderIDs(ctx context.Context, offset, limit int) ([]uint32, error) {
    var res []uint32

    query := `SELECT id FROM "order" WHERE is_terminated = false LIMIT $1 OFFSET $2;`

    rows, err := r.slave.Query(ctx, query, limit, offset)
    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
}

Thus, the function safely closes resources and correctly handles errors.