5

Using postgres 9.3, go 1.6

I've been trying to use transactions with the go pq library.

// Good
txn, _ := db.Begin()
txn.Query("UPDATE t_name SET a = 1")
err := txn.Commit() // err is nil

// Bad
txn, _ := db.Begin()
txn.Query("UPDATE t_name SET a = $1", 1)
err := txn.Commit() // Gives me a "unexpected command tag Q" error
// although the data is committed

For some reason, when I execute a Query with parameters, I always get an unexpected command tag Q error from the Commit(). What is this error (what is Q?) and why am I getting it?

I believe this is where the error is created.

3
  • 1
    Your statement does not return any rows. Try Exec. Q is the protocol identifier sent to the backend for a query, for an execute it sends E. Commented Mar 29, 2016 at 22:22
  • You're ignoring the error returns from db.Begin() and txn.Query(); possibly one of those has an error that may shed some light on the issue before the txn.Commit() Commented Mar 30, 2016 at 2:12
  • @DmitriGoldring, Thanks! That solved it. Commented Mar 30, 2016 at 3:05

1 Answer 1

10

To start of i agree whit Dmitri from the comments, in this case you should probably use Exec.

However after receiving this same issue I started digging:

Query returns 2 arguments a Rows pointer and an error. What you always have to do with a Rows object is to close it when you are don with it:

// Fixed
txn, _ := db.Begin()
rows, _ := txn.Query("UPDATE t_name SET a = $1", 1)
//Read out rows
rows.Close() //<- This will solve the error
err := txn.Commit()

I was however unable to see any difference in the traffic to the database when using rows.Close() witch indicates to me that this might be a bug in pq.

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

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.