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.

Derek
  • 11,980
  • 26
  • 103
  • 162
  • 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. – Dmitri Goldring Mar 29 '16 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()` – John Weldon Mar 30 '16 at 02:12
  • @DmitriGoldring, Thanks! That solved it. – Derek Mar 30 '16 at 03:05

1 Answers1

11

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.

KilledKenny
  • 385
  • 4
  • 19