GoLang rows.Scan() messing up my order. How do I keep the order?

Viewed 40

So basically I got an Array filled with 5 IDs. First the ProjectId and 4 ProductIds.

[projectId1 productid1 productid2 productid3 productid4]

I use a custom Query to get these Products by Id.

It looks like this:

func (q *Queries) GetProductsByIdsAndProjektId(ctx context.Context, arg GetProductsByIdsAndProjektIdParams) ([]Products, error) {
    stmt := createGetProductsByIdsAndProjektId(len(arg.ProductIds))
    args := make([]interface{}, len(arg.ProductIds)+1)
    args[0] = arg.ProjektID
    for i, id := range arg.ProductIds {
        args[i+1] = id
    }

    rows, err := q.db.QueryContext(ctx, stmt, args...)
    if err != nil {
        return nil, err
    }
    defer rows.Close()
    var items []Products
    for rows.Next() {
        var i Product
        if err := rows.Scan(
            &i.ID,
            &i.ProjektID,
            &i.Name,
            &i.Price,
        ); err != nil {
            return nil, err
        }
        items = append(items, i)
    }

But when I log.Info(i) it scans the ids in a different order. for example the items array will look like this in the end

[product4data product2data product3data product1data]

It is always the same order but not the one given to it with args. Is there a way to force rows.Next() -> rows.Scan() from the first id in an array to the last, so the items array will have all data for the 4 products in the same order the ids were given? So it should be

[product1Data product2Data product3Data product4Data]

instead.

0 Answers
Related