gastownhall/beads · error

failed to get previous external_ref: %w

Error message

failed to get previous external_ref: %w

What it means

PreviousExternalRefInTx wraps an unexpected database error from querying the most recent external_ref before a given timestamp. sql.ErrNoRows is handled separately and is NOT an error (returns "", false, nil); only genuine driver/query failures reach this wrapper.

Source

Thrown at internal/storage/issueops/history.go:128

//
// The subquery wrapper avoids Dolt's max1Row optimization on PK lookup, for
// the same reason described on HistoryInTx above.
func PreviousExternalRefInTx(ctx context.Context, tx *sql.Tx, issueID string, asOf time.Time) (string, bool, error) {
	var previousRef sql.NullString
	err := tx.QueryRowContext(ctx, `
		SELECT external_ref
		FROM (
			SELECT id, external_ref, commit_date FROM dolt_history_issues
		) h
		WHERE h.id = ? AND h.commit_date <= ?
		ORDER BY h.commit_date DESC
		LIMIT 1
	`, issueID, asOf.UTC()).Scan(&previousRef)
	if err == sql.ErrNoRows {
		return "", false, nil
	}
	if err != nil {
		return "", false, fmt.Errorf("failed to get previous external_ref: %w", err)
	}
	return previousRef.String, true, nil
}

View on GitHub (pinned to 71377f2769)

Solutions

  1. Inspect the wrapped driver error to identify the root cause
  2. Verify the issues table and external_ref column exist in the schema
  3. Check database connectivity and transaction state
  4. Retry the transaction; transient Dolt/SQL errors often resolve on retry

Example fix

null
Defensive patterns

Strategy: try-catch

Validate before calling

var n int
err := db.QueryRow("SELECT COUNT(*) FROM information_schema.columns WHERE table_name='issues' AND column_name='external_ref'").Scan(&n)
if n == 0 { /* run migration */ }

Type guard

null

Try / catch

ref, ok, err := issueops.PreviousExternalRefInTx(ctx, tx, issueID, asOf)
if err != nil {
  if isTransient(err) { return retry(...) }
  return fmt.Errorf("previous external_ref lookup failed: %w", err)
}

Prevention

When it happens

Trigger: The query `SELECT external_ref ... ORDER BY ... LIMIT 1` fails due to table not existing, connection loss, lock timeout, or malformed timestamp argument conversion.

Common situations: Database unavailable mid-transaction; schema drift removing the external_ref column; Dolt backend hiccup or lock contention under concurrent writers.

Understand the failure class

Background: "query failed", "%w: SQL error" — wrapped database query errors in Go libraries explained — this error's family across 3 libraries.

Related errors


AI-assisted analysis of gastownhall/beads@71377f2769 (2026-08-30). Data as JSON: /api/errors/32fe546d0940919f. Report an issue: GitHub.