0

A peculiar error occurred today when was manipulating data in Postgres using database/sql and driver github.com/lib/pq. I have the following SQL schema created in Postgres:

CREATE TABLE IF NOT EXISTS bench_bytea (
    id INT PRIMARY KEY,
    name VARCHAR,
    data BYTEA
);

A very basic table containing a data blob of type BYTEA.

I then tried to execute simple INSERT statement using the Exec() function provided by database/sql. Here it is:

psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
    "password=%s dbname=%s sslmode=disable",
    host, port, user, password, dbname)

db, err := sql.Open("postgres", psqlInfo)
if err != nil {
    panic(err)
}
defer db.Close()

stmt := `INSERT INTO bench_bytea (id, name, data) VALUES ($1, $2, $3) ON CONFLICT (id) DO NOTHING`
data := `{"title": "Sleeping Beauties", "genres": ["Fiction", "Thriller", "Horror"], "published": false}`
i := 0

_, err = db.Exec(stmt, i, "testing "+string(i), []byte(data))
if err != nil {
    panic(err)
}

The key highlight happens on the db.Exec() line where I execute a SQL INSERT statement (in practicality i is an index of an array where I stored different testing data. I didn't want to include the other pieces of data here since it's really long and irrelevant). The error I received is:

pq: invalid byte sequence for encoding "UTF8": 0x00

Now if I change "testing "+string(i) into "testing", the error is gone. That is, if I didn't insert a concatenating strings into the name column, there's no error. What is going on here?

4
  • 1
    Use strconv.Itoa to convert an integer to string. Commented Dec 17, 2019 at 23:57
  • ... play.golang.com/p/3gZ9el8x5Fa Commented Dec 17, 2019 at 23:58
  • golang.org/ref/spec#Conversions_to_and_from_a_string_type "Converting a signed or unsigned integer value to a string type yields a string containing the UTF-8 representation of the integer. " (not the integer) Commented Dec 18, 2019 at 0:01
  • Ah... I'll answer my own question then. Commented Dec 18, 2019 at 0:08

1 Answer 1

2

You can't convert an integer to a string like that. The result of string(0) is "\x00", aka a null byte, instead of "0" which is probably you want. You should use strconv.Itoa for the conversion instead.

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.