jackc/pgx · error

rewrite query failed

Error message

rewrite query failed: %w

What it means

A custom QueryRewriter supplied via query options failed while rewriting the SQL and arguments before execution. The rewriter's own error is wrapped with %w; pgx itself did not fail — the user-provided RewriteQuery callback did.

Solutions

  1. Unwrap the error with errors.Unwrap or errors.As to inspect the rewriter's failure
  2. Fix the bug inside the custom QueryRewriter implementation
  3. Test the rewriter independently of query execution
Defensive patterns

Strategy: try-catch

When it happens

Trigger: Thrown at conn.go:515 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of jackc/pgx@ec1a0befd2 (2026-08-04). Data as JSON: /api/errors/7f0521229c7ee3e4. Report an issue: GitHub.

Appendix: source

Thrown at conn.go:515

optionLoop:
	for len(arguments) > 0 {
		switch arg := arguments[0].(type) {
		case QueryExecMode:
			mode = arg
			arguments = arguments[1:]
		case QueryRewriter:
			queryRewriter = arg
			arguments = arguments[1:]
		default:
			break optionLoop
		}
	}

	if queryRewriter != nil {
		sql, arguments, err = queryRewriter.RewriteQuery(ctx, c, sql, arguments)
		if err != nil {
			return pgconn.CommandTag{}, fmt.Errorf("rewrite query failed: %w", err)
		}
	}

	// Always use simple protocol when there are no arguments.
	if len(arguments) == 0 {
		mode = QueryExecModeSimpleProtocol
	}

	defer func() {
		if err != nil {
			if sc := c.statementCache; sc != nil {
				sc.Invalidate(sql)
			}

			if sc := c.descriptionCache; sc != nil {
				sc.Invalidate(sql)
			}
		}

View on GitHub (pinned to ec1a0befd2)