Skip to content

Not working insert struct with []byte (BYTEA) field #1194

@uginroot

Description

@uginroot

Inserting structures with properties of type []byte into a column of type BYTEA does not always work.

Example:

package main

import (
	"database/sql"
	"github.com/doug-martin/goqu/v9"
	"github.com/jmoiron/sqlx"
	_ "github.com/lib/pq"
)

type ByteaTest struct {
	Payload []byte `db:"payload"`
}

func NewConnection() *sqlx.DB {
	connectionString := "host=localhost port=5432 user=admin password=test dbname=test sslmode=require"
	db, err := sql.Open("postgres", connectionString)
	if err != nil {
		panic(err)
	}
	return sqlx.NewDb(db, "postgres")
}

func main() {
	connection := NewConnection()
	dialect := goqu.Dialect("postgres")
	db := dialect.DB(connection)
	db.Exec(`
		CREATE TABLE IF NOT EXISTS bytea_test (
    			id BIGSERIAL PRIMARY KEY,
    			payload BYTEA NOT NULL
		)`,
	)
	defer func() {
		db.Exec("DROP TABLE IF EXISTS bytea_test")
		connection.Close()
	}()
	byteaTest := &ByteaTest{
		Payload: []byte{10, 38, 103, 111, 111, 103, 108, 101, 95, 115, 104,
			111, 112, 112, 105, 110, 103, 46, 85, 112, 100, 97, 116, 101, 80, 114, 111,
			103, 114, 101, 115, 115, 77, 101, 116, 97, 100, 97, 116, 97, 18, 21, 8, 3,
			56, 0, 66, 13, 49, 55, 52, 57, 55, 48, 51, 56, 48, 55, 54, 53, 56, 72, 1},
	}
	_, err := db.Insert("bytea_test").Rows(byteaTest).Executor().Exec()
	if err != nil {
		panic(err) // panic: pq: invalid message format
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions