Skip to content

How do I find failed statements in a batch so I can take them out and the rest can be successful on retry? #1550

Answered by jackc
ns-gzhang asked this question in Q&A
Discussion options

You must be logged in to vote

Is there a way to tell which statements caused failure in a batch?

I think you should be able to find which statement failed by calling Query on https://pkg.go.dev/github.com/jackc/pgx/v5#QueuedQuery before sending the batch.

package main

import (
	"context"
	"fmt"
	"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)

	batch := &pgx.Batch{}

	batch.Queue(`select 1`).Query(func(rows pgx.Rows) error {
		rows.Close()
		if err := rows.Err(); err != nil {
			return fmt.Errorf("first query: %w", err)
		}

		return nil
	})

	batch.Queue(`sele…

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@ns-gzhang
Comment options

@jackc
Comment options

@ns-gzhang
Comment options

Answer selected by ns-gzhang
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