Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang postgres Commit unknown command error?

Tags:

postgresql

go

pq

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.

like image 659
Derek Avatar asked Mar 29 '16 21:03

Derek


1 Answers

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.

like image 118
KilledKenny Avatar answered Nov 13 '22 23:11

KilledKenny