Last active
December 14, 2015 01:09
-
-
Save eaigner/5004468 to your computer and use it in GitHub Desktop.
bytea bug
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"database/sql" | |
_ "github.com/bmizerany/pq" | |
"log" | |
) | |
func main() { | |
query(true) | |
query(false) | |
} | |
var lastExecErr error | |
func setErr(r sql.Result, e error) { | |
if lastExecErr == nil { | |
lastExecErr = e | |
} | |
} | |
func query(withBytea bool) { | |
log.Printf("WITH BYTEA: %t", withBytea) | |
db, err := sql.Open("postgres", "dbname=<name> host=<host> user=<user> password=<password> port=5432 sslmode=require") | |
if err != nil { | |
panic(err) | |
} | |
// Create a table | |
setErr(db.Exec(`DROP TABLE "gotest"`)) | |
// With/out bytea field | |
if withBytea { | |
setErr(db.Exec(`CREATE TABLE "gotest" ( "id" bigserial, "cid" varchar(20), "image" bytea NOT NULL)`)) | |
setErr(db.Exec(`INSERT INTO "gotest" ( "cid", "image") VALUES ( 'cid-7afc3de5', decode('013d7d16d7ad4fefb61bd95b765c8ceb', 'hex') )`)) | |
} else { | |
setErr(db.Exec(`CREATE TABLE "gotest" ( "id" bigserial, "cid" varchar(20))`)) | |
setErr(db.Exec(`INSERT INTO "gotest" ( "cid" ) VALUES ( 'cid-7afc3de5' )`)) | |
} | |
if lastExecErr != nil { | |
panic(err) | |
} | |
rows, err := db.Query(`SELECT * FROM "gotest"`) | |
if err != nil { | |
panic(err) | |
} | |
num := 0 | |
for rows.Next() { | |
num++ | |
var id int | |
var cid string | |
var image []byte | |
if withBytea { | |
err = rows.Scan(&id, &cid, &image) | |
if err != nil { | |
panic(err) | |
} | |
} else { | |
err = rows.Scan(&id, &cid) | |
if err != nil { | |
panic(err) | |
} | |
} | |
log.Printf("id: %d, cid: %s, image: %x", id, cid, image) | |
} | |
log.Printf("%d rows processed", num) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment