Skip to content

How to find record in table by hex value in bytea column? #1649

Answered by jackc
stasvo asked this question in Q&A
Discussion options

You must be logged in to vote

You should be able to use a []byte as an bytea parameter. hex.DecodeString should have done what you want.

package main

import (
	"context"
	"encoding/hex"
	"log"
	"os"

	"github.com/jackc/pgx/v5"
)

func main() {
	ctx := context.Background()

	conn, err := pgx.Connect(ctx, os.Getenv("DATABASE_URL"))
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close(ctx)

	b, err := hex.DecodeString("01020304")
	if err != nil {
		log.Fatal(err)
	}

	var isEqual bool
	err = conn.QueryRow(ctx, `select '\x01020304'::bytea = $1::bytea`, b).Scan(&isEqual)
	if err != nil {
		log.Fatal(err)
	}

	log.Println("isEqual:", isEqual)
}
jack@glados ~/dev/pgx_issues/pgx-1649 ±master⚡ » go run .
2023/06/18 06:56:25…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@stasvo
Comment options

Answer selected by stasvo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants