Golang postgres Commit unknown command error?
Asked Answered
L

1

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.

Lucania answered 29/3, 2016 at 21:59 Comment(3)
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.Labialize
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()Lymphangial
@DmitriGoldring, Thanks! That solved it.Lucania
D
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.

Detestation answered 26/4, 2016 at 13:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.