-
I'm using a batch to insert/update a table with dynamically generated statements. When there is one statement that fails, the entire batch will fail, and there seems no status for individual success or failure in the batch (as |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
I think you should be able to find which statement failed by calling 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(`select 1 / n from generate_series(-5, 5) n`).Query(func(rows pgx.Rows) error {
rows.Close()
if err := rows.Err(); err != nil {
return fmt.Errorf("second query: %w", err)
}
return nil
})
batch.Queue(`select 1`).Query(func(rows pgx.Rows) error {
rows.Close()
if err := rows.Err(); err != nil {
return fmt.Errorf("third query: %w", err)
}
return nil
})
err = conn.SendBatch(ctx, batch).Close()
fmt.Println("err:", err)
} However, this will only work if the queries are executed. If there is a problem such as a syntax error no Presumably, the batch system could be modified to wrap errors with something that included the query index but nobody has built that yet.
Well, not using a batch is the simplest way of course. If the network round trips are a problem then another option is pipeline mode down in the pgconn layer. But that is much lower level and difficult to use. |
Beta Was this translation helpful? Give feedback.
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.