2

Given the following function:

func (me *OrderService) GetOrders(orderTx *sql.Tx, orderId int) (orders *sql.Rows) {
    orders, err := ecommTx.Query("SELECT * FROM orders WHERE id=?", orderId)
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("Successfully queried and receive %d orders", orders.count)
    return orders
}

Are there any easy ways to .count the results? I'd like to keep this database engine agonistic, but FWIW.... I'm using Matt N's sqlite3 driver for my integration tests, but plan on having a different DB in prod.

1
  • SELECT count(*) FROM orders WHERE id=.... Commented Feb 27, 2014 at 15:56

2 Answers 2

4

There is no portable way to know the number of rows returned by a statement in advance, meaning without iterating through the returned cursor and counting.

There are two typical solutions to this:

  • Run a separate COUNT(*) query. The problem with this approach is that it's very racy (the result set can be modified between the two queries, at least in some transaction isolation modes), so it is really only useful for things like pagers where you do a query that returns only part of the result set, and want to know how many other rows there are.

  • Iterate through the cursor and count. In Go, that means calling .Next() and then .Scan the result into your Order struct.

Sign up to request clarification or add additional context in comments.

Comments

3

sql.Query() returns *Rows. Rows is a reader, not a collection, so calls such as count() or len() etc. are not relevant. You have to read through Rows to know how many entries you've got:

count := 0
for orders.Next() {
    count++
}

log.Printf("Successfully queried and receive %d orders", count)

You are not adding any extra overhead by doing so. Other languages, such as C# or Delphi, that might return a collection with a count property are simply doing the reading for you and packaging the results into a collection for your convenience.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.