diff --git a/cmd/bd/conflicts.go b/cmd/bd/conflicts.go new file mode 100644 index 000000000..71aaec12e --- /dev/null +++ b/cmd/bd/conflicts.go @@ -0,0 +1,524 @@ +package main + +import ( + "context" + "fmt" + "sort" + "strings" + + "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/versioncontrolops" + "github.com/steveyegge/beads/internal/ui" +) + +// `bd conflicts` is the operator surface for a merge that halted (federation +// ask #3). Without it, resolving means dropping into the raw dolt CLI inside +// .beads/dolt/ — `dolt conflicts cat issues`, `dolt conflicts resolve +// --ours issues`, `dolt add -A && dolt commit` — whose flag surface differs +// from git's just enough to bite. Here the same work is issue-oriented: which +// issues are conflicted, what each side says field by field, and a resolution +// that can name a single issue instead of a whole table. +// +// It reads the LIVE working set. beads' own pull path auto-resolves the safe +// conflict classes and aborts anything else (restoring the working set), so +// what lands here is what a CLI-level pull — the federation bridge's — left +// behind, plus anything a `bd vc merge` left unresolved. + +const conflictsResolveHint = "Resolve with: bd conflicts resolve --ours|--theirs" + +var conflictsCmd = &cobra.Command{ + Use: "conflicts", + GroupID: "sync", + Short: "Inspect and resolve live merge conflicts", + Long: `Inspect and resolve the merge conflicts sitting in the working set. + +Conflicts appear when a pull or merge brought in changes that collide with +local ones and could not be settled automatically. These commands present them +per issue and per field, and resolve them without the raw dolt CLI. + +Examples: + bd conflicts list # which tables and issues are conflicted + bd conflicts show # every conflicted row, field by field + bd conflicts show bd-1234 # one issue + bd conflicts resolve bd-1234 --ours # keep our side of one issue + bd conflicts resolve --all --theirs # take their side of everything`, +} + +var ( + conflictsShowAllFields bool + conflictsShowTable string + conflictsResolveOurs bool + conflictsResolveTheirs bool + conflictsResolveStrat string + conflictsResolveAll bool + conflictsResolveTable string + conflictsNoCommit bool +) + +var conflictsListCmd = &cobra.Command{ + Use: "list", + Short: "List tables and issues with live merge conflicts", + Args: cobra.NoArgs, + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + defer conflictsMetrics("conflicts-list")() + ctx := rootCtx + if err := requireConflictSupport(); err != nil { + return err + } + tables, err := conflictedTables(ctx) + if err != nil { + return HandleErrorRespectJSON("failed to read conflicts: %v", err) + } + type tableOut struct { + Table string `json:"table"` + Count int `json:"count"` + Keys []string `json:"keys,omitempty"` + } + out := make([]tableOut, 0, len(tables)) + total := 0 + for _, t := range tables { + rows, err := conflictRows(ctx, t.Field) + if err != nil { + return HandleErrorRespectJSON("failed to read conflicts for %s: %v", t.Field, err) + } + keys := make([]string, 0, len(rows)) + for _, r := range rows { + if r.Key != "" { + keys = append(keys, r.Key) + } + } + // dolt_conflicts' own count is authoritative for tables whose + // rows we could not key (keyless tables list no keys). + count := len(rows) + if count == 0 { + count = t.Count + } + total += count + out = append(out, tableOut{Table: t.Field, Count: count, Keys: keys}) + } + if jsonOutput { + return outputJSON(map[string]interface{}{ + "conflicts": total, + "tables": out, + }) + } + if total == 0 { + fmt.Println("No merge conflicts.") + return nil + } + fmt.Printf("\n%s %d live merge conflict(s):\n\n", ui.RenderAccent("!!"), total) + for _, t := range out { + fmt.Printf(" %s (%d)\n", ui.RenderAccent(t.Table), t.Count) + for _, k := range t.Keys { + fmt.Printf(" %s\n", k) + } + } + fmt.Printf("\nInspect with: bd conflicts show []\n%s\n\n", conflictsResolveHint) + return nil + }, +} + +var conflictsShowCmd = &cobra.Command{ + Use: "show []", + Short: "Show conflicted rows field by field (base/ours/theirs)", + Long: `Show each conflicted row with its fields side by side. + +Only fields where our side and their side disagree are shown; --all-fields +shows every column. Without an issue ID, every conflicted row of every +conflicted table is shown.`, + Args: cobra.MaximumNArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + defer conflictsMetrics("conflicts-show")() + ctx := rootCtx + if err := requireConflictSupport(); err != nil { + return err + } + wantKey := "" + if len(args) == 1 { + wantKey = args[0] + } + + var tables []string + if conflictsShowTable != "" { + tables = []string{conflictsShowTable} + } else { + ts, err := conflictedTables(ctx) + if err != nil { + return HandleErrorRespectJSON("failed to read conflicts: %v", err) + } + for _, t := range ts { + tables = append(tables, t.Field) + } + } + + var matched []storage.ConflictRow + for _, table := range tables { + rows, err := conflictRows(ctx, table) + if err != nil { + return HandleErrorRespectJSON("failed to read conflicts for %s: %v", table, err) + } + for _, r := range rows { + if wantKey != "" && r.Key != wantKey { + continue + } + matched = append(matched, r) + } + } + + if jsonOutput { + return outputJSON(map[string]interface{}{ + "conflicts": len(matched), + "rows": filterShownFields(matched, conflictsShowAllFields), + }) + } + if len(matched) == 0 { + if wantKey != "" { + fmt.Printf("No live merge conflict for %s.\n", wantKey) + } else { + fmt.Println("No merge conflicts.") + } + return nil + } + for _, r := range matched { + printConflictRow(r, conflictsShowAllFields) + } + fmt.Printf("%s\n\n", conflictsResolveHint) + return nil + }, +} + +var conflictsResolveCmd = &cobra.Command{ + Use: "resolve [...]", + Short: "Resolve merge conflicts with --ours or --theirs", + Long: `Resolve live merge conflicts, then conclude the merge with a commit. + +Named issue IDs are resolved row by row, leaving every other conflicted row +alone. --all resolves whole tables at once (dolt's own table-level +resolution). The merge is committed only once NO conflicts remain, so a +partial resolution leaves the merge open for the next pass. + +Row-by-row resolution requires the row to exist on both sides: when one side +deleted it, resolve that table wholesale or edit the row directly. + +Examples: + bd conflicts resolve bd-1234 --ours # keep our side of one issue + bd conflicts resolve bd-1234 bd-5678 --theirs # take their side of two + bd conflicts resolve --all --ours # every conflicted table + bd conflicts resolve --all --table config --theirs`, + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + defer conflictsMetrics("conflicts-resolve")() + ctx := rootCtx + if err := requireConflictSupport(); err != nil { + return err + } + strategy, err := resolveStrategy() + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + if conflictsResolveAll == (len(args) > 0) { + return HandleErrorRespectJSON("name the issue IDs to resolve, or pass --all (not both)") + } + + // Pre-resolution HEAD scopes the is_blocked recompute the merged-in + // writes bypassed, exactly as bd vc merge does (bd-578h9.11). + preHead, _ := store.GetCurrentCommit(ctx) + + resolved := 0 + if conflictsResolveAll { + tables := []string{} + if conflictsResolveTable != "" { + tables = append(tables, conflictsResolveTable) + } else { + ts, err := conflictedTables(ctx) + if err != nil { + return HandleErrorRespectJSON("failed to read conflicts: %v", err) + } + for _, t := range ts { + tables = append(tables, t.Field) + } + } + if len(tables) == 0 { + fmt.Println("No merge conflicts.") + return nil + } + for _, table := range tables { + rows, err := conflictRows(ctx, table) + if err != nil { + return HandleErrorRespectJSON("failed to read conflicts for %s: %v", table, err) + } + if err := store.ResolveConflicts(ctx, table, strategy); err != nil { + return HandleErrorRespectJSON("failed to resolve conflicts in %s: %v", table, err) + } + resolved += len(rows) + } + } else { + table := conflictsResolveTable + if table == "" { + table = "issues" + } + inspector, ok := conflictInspector() + if !ok { + return HandleErrorRespectJSON("this backend does not support per-issue conflict resolution; use --all") + } + if !versioncontrolops.SupportsRowResolve(table) { + return HandleErrorRespectJSON("per-issue resolution is not supported for table %s; use --all --table %s", table, table) + } + n, err := inspector.ResolveConflictRows(ctx, table, args, strategy) + if err != nil { + // A partial resolution is real state: report what landed. + if n > 0 { + return HandleErrorRespectJSON("resolved %d of %d conflict(s) before failing: %v", n, len(args), err) + } + return HandleErrorRespectJSON("failed to resolve conflicts: %v", err) + } + resolved = n + } + + remaining, err := totalConflicts(ctx) + if err != nil { + return HandleErrorRespectJSON("resolved %d conflict(s) but failed to re-check conflicts: %v", resolved, err) + } + + committed := false + if resolved > 0 && remaining == 0 && !conflictsNoCommit { + // CommitMergeResolution, not Commit: server-mode Commit excludes + // the config table (GH#2455), so a resolved config conflict would + // be dropped and the merge would re-wedge on the next pull + // (GH#2474). + msg := fmt.Sprintf("Resolve %d merge conflict(s) using %s strategy", resolved, strategy) + if err := store.CommitMergeResolution(ctx, msg); err != nil { + return HandleErrorRespectJSON("conflicts resolved but commit failed: %v", err) + } + committed = true + // Same unwrap rule as conflictInspector: RecomputeBlockedAfterMerge + // lives on the concrete Dolt store, not on DoltStorage. + if rs, ok := storage.UnwrapStore(store).(interface { + RecomputeBlockedAfterMerge(ctx context.Context, fromCommit string) error + }); ok { + if err := rs.RecomputeBlockedAfterMerge(ctx, preHead); err != nil { + return HandleErrorRespectJSON("conflicts resolved but is_blocked recompute failed: %v", err) + } + } + } + + if jsonOutput { + return outputJSON(map[string]interface{}{ + "resolved": resolved, + "strategy": strategy, + "remaining": remaining, + "committed": committed, + }) + } + fmt.Printf("Resolved %d conflict(s) using '%s'.\n", resolved, strategy) + switch { + case remaining > 0: + fmt.Printf("%d conflict(s) remain; the merge is not committed yet.\nRun: bd conflicts list\n", remaining) + case committed: + fmt.Println("Merge committed. Push when ready: bd sync") + case resolved == 0: + fmt.Println("Nothing was conflicted; no commit made.") + default: + fmt.Println("All conflicts resolved; commit withheld. Conclude the merge with: bd dolt commit") + } + return nil + }, +} + +// conflictsMetrics starts a command metrics event and returns its closer, so +// each subcommand can arm it with one deferred call. +func conflictsMetrics(name string) func() { + evt := metrics.NewCommandEvent(name) + return func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + } +} + +// requireConflictSupport refuses the modes where conflict inspection has no +// meaning: a proxied server owns its own working set, and a non-Dolt backend +// has no merge state at all. +func requireConflictSupport() error { + if usesProxiedServer() { + return HandleErrorRespectJSON("bd conflicts is not supported in proxied-server mode") + } + if store == nil { + return HandleErrorRespectJSON("no database open") + } + return nil +} + +// conflictedTables returns the tables dolt reports as conflicted. +func conflictedTables(ctx context.Context) ([]storage.Conflict, error) { + conflicts, err := store.GetConflicts(ctx) + if err != nil { + return nil, err + } + sort.Slice(conflicts, func(i, j int) bool { return conflicts[i].Field < conflicts[j].Field }) + return conflicts, nil +} + +// conflictInspector returns the store's conflict surface. store is ALWAYS +// wrapped (telemetry, and the hook-firing decorator whenever hooks are on), +// and a decorator that embeds the DoltStorage interface promotes only that +// interface's methods — so asserting ConflictInspector on the wrapper is +// always false and every conflict would read as "no conflicts". UnwrapStore +// is the codebase's answer for optional interfaces (hook_decorator.go:67). +func conflictInspector() (storage.ConflictInspector, bool) { + inspector, ok := storage.UnwrapStore(store).(storage.ConflictInspector) + return inspector, ok +} + +// conflictRows returns the per-field conflicted rows of one table, or an empty +// slice when the backend has no ConflictInspector. +func conflictRows(ctx context.Context, table string) ([]storage.ConflictRow, error) { + inspector, ok := conflictInspector() + if !ok { + return nil, nil + } + return inspector.GetConflictRows(ctx, table) +} + +// totalConflicts counts every live conflicted row, the gate on committing the +// merge: dolt refuses a commit while any conflict is live. +func totalConflicts(ctx context.Context) (int, error) { + tables, err := conflictedTables(ctx) + if err != nil { + return 0, err + } + total := 0 + for _, t := range tables { + total += t.Count + } + return total, nil +} + +// resolveStrategy reads the strategy from --ours/--theirs/--strategy. +func resolveStrategy() (string, error) { + picked := "" + switch { + case conflictsResolveOurs && conflictsResolveTheirs: + return "", fmt.Errorf("pass --ours or --theirs, not both") + case conflictsResolveOurs: + picked = versioncontrolops.ConflictStrategyOurs + case conflictsResolveTheirs: + picked = versioncontrolops.ConflictStrategyTheirs + } + if conflictsResolveStrat != "" { + if picked != "" && picked != conflictsResolveStrat { + return "", fmt.Errorf("--strategy %s contradicts --%s", conflictsResolveStrat, picked) + } + picked = conflictsResolveStrat + } + if picked == "" { + return "", fmt.Errorf("a resolution strategy is required: --ours or --theirs") + } + if err := versioncontrolops.ValidateConflictStrategy(picked); err != nil { + return "", err + } + return picked, nil +} + +// filterShownFields drops the agreeing fields from JSON output unless the +// caller asked for all of them, so a conflict reads as its handful of +// diverged fields rather than the whole row. +func filterShownFields(rows []storage.ConflictRow, allFields bool) []storage.ConflictRow { + if allFields { + return rows + } + out := make([]storage.ConflictRow, 0, len(rows)) + for _, r := range rows { + trimmed := r + trimmed.Fields = differingFields(r.Fields) + out = append(out, trimmed) + } + return out +} + +func differingFields(fields []storage.ConflictFieldValue) []storage.ConflictFieldValue { + out := make([]storage.ConflictFieldValue, 0, len(fields)) + for _, f := range fields { + if f.Differs() { + out = append(out, f) + } + } + return out +} + +// printConflictRow renders one conflicted row for humans. +func printConflictRow(r storage.ConflictRow, allFields bool) { + key := r.Key + if key == "" { + key = "(unkeyed row)" + } + fmt.Printf("\n%s %s [%s]\n", ui.RenderAccent(r.Table), key, conflictKind(r)) + fields := r.Fields + if !allFields { + fields = differingFields(fields) + } + if len(fields) == 0 { + fmt.Println(" (no differing fields; the conflict is structural)") + return + } + for _, f := range fields { + fmt.Printf(" %s\n", f.Name) + fmt.Printf(" base: %s\n", conflictValue(f.Base)) + fmt.Printf(" ours: %s\n", conflictValue(f.Ours)) + fmt.Printf(" theirs: %s\n", conflictValue(f.Theirs)) + } + fmt.Println() +} + +// conflictKind names the conflict class in the vocabulary an operator needs to +// choose a strategy, since ours/theirs mean different things per class. +func conflictKind(r storage.ConflictRow) string { + switch { + case !r.OurExists && !r.TheirExists: + return "both sides deleted" + case !r.OurExists: + return "we deleted / they modified" + case !r.TheirExists: + return "we modified / they deleted" + case !r.BaseExists: + return "both sides added" + default: + return "both sides modified" + } +} + +// conflictValue renders a field value, distinguishing SQL NULL from empty. +func conflictValue(v *string) string { + if v == nil { + return "(null)" + } + s := strings.ReplaceAll(*v, "\n", "\\n") + if s == "" { + return `""` + } + return s +} + +func init() { + conflictsShowCmd.Flags().BoolVar(&conflictsShowAllFields, "all-fields", false, "Show every column, not just the fields that diverged") + conflictsShowCmd.Flags().StringVar(&conflictsShowTable, "table", "", "Restrict to one conflicted table (default: all)") + + conflictsResolveCmd.Flags().BoolVar(&conflictsResolveOurs, "ours", false, "Keep our side") + conflictsResolveCmd.Flags().BoolVar(&conflictsResolveTheirs, "theirs", false, "Take their side") + conflictsResolveCmd.Flags().StringVar(&conflictsResolveStrat, "strategy", "", "Resolution strategy: ours|theirs") + conflictsResolveCmd.Flags().BoolVar(&conflictsResolveAll, "all", false, "Resolve whole tables instead of named issues") + conflictsResolveCmd.Flags().StringVar(&conflictsResolveTable, "table", "", "Table to resolve (default: issues)") + conflictsResolveCmd.Flags().BoolVar(&conflictsNoCommit, "no-commit", false, "Resolve without committing the merge") + + conflictsCmd.AddCommand(conflictsListCmd) + conflictsCmd.AddCommand(conflictsShowCmd) + conflictsCmd.AddCommand(conflictsResolveCmd) + rootCmd.AddCommand(conflictsCmd) +} diff --git a/cmd/bd/conflicts_test.go b/cmd/bd/conflicts_test.go new file mode 100644 index 000000000..49ba8d15d --- /dev/null +++ b/cmd/bd/conflicts_test.go @@ -0,0 +1,128 @@ +package main + +import ( + "testing" + + "github.com/steveyegge/beads/internal/storage" +) + +func strp(s string) *string { return &s } + +func resetConflictResolveFlags() { + conflictsResolveOurs = false + conflictsResolveTheirs = false + conflictsResolveStrat = "" +} + +func TestResolveStrategy(t *testing.T) { + t.Cleanup(resetConflictResolveFlags) + + cases := []struct { + name string + ours bool + theirs bool + strat string + want string + wantErr bool + }{ + {name: "ours flag", ours: true, want: "ours"}, + {name: "theirs flag", theirs: true, want: "theirs"}, + {name: "strategy flag", strat: "theirs", want: "theirs"}, + {name: "agreeing flags", ours: true, strat: "ours", want: "ours"}, + {name: "both sides", ours: true, theirs: true, wantErr: true}, + {name: "contradiction", ours: true, strat: "theirs", wantErr: true}, + {name: "unset", wantErr: true}, + {name: "garbage strategy", strat: "mine", wantErr: true}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + resetConflictResolveFlags() + conflictsResolveOurs = c.ours + conflictsResolveTheirs = c.theirs + conflictsResolveStrat = c.strat + got, err := resolveStrategy() + if c.wantErr { + if err == nil { + t.Fatalf("resolveStrategy() = %q, want an error", got) + } + return + } + if err != nil { + t.Fatalf("resolveStrategy() error = %v", err) + } + if got != c.want { + t.Errorf("resolveStrategy() = %q, want %q", got, c.want) + } + }) + } +} + +func TestDifferingFieldsDropsAgreement(t *testing.T) { + fields := []storage.ConflictFieldValue{ + {Name: "id", Base: strp("bd-1"), Ours: strp("bd-1"), Theirs: strp("bd-1")}, + {Name: "status", Base: strp("open"), Ours: strp("closed"), Theirs: strp("open")}, + {Name: "assignee", Ours: strp("zelda"), Theirs: nil}, + } + got := differingFields(fields) + if len(got) != 2 { + t.Fatalf("want status and assignee, got %d fields: %+v", len(got), got) + } + if got[0].Name != "status" || got[1].Name != "assignee" { + t.Errorf("differing fields = %q,%q", got[0].Name, got[1].Name) + } +} + +func TestFilterShownFieldsHonorsAllFields(t *testing.T) { + rows := []storage.ConflictRow{{ + Table: "issues", + Key: "bd-1", + Fields: []storage.ConflictFieldValue{ + {Name: "id", Ours: strp("bd-1"), Theirs: strp("bd-1")}, + {Name: "status", Ours: strp("open"), Theirs: strp("closed")}, + }, + }} + if got := filterShownFields(rows, true); len(got[0].Fields) != 2 { + t.Errorf("--all-fields must keep every column, got %d", len(got[0].Fields)) + } + got := filterShownFields(rows, false) + if len(got[0].Fields) != 1 || got[0].Fields[0].Name != "status" { + t.Errorf("default view = %+v, want only the diverged field", got[0].Fields) + } + // The caller's slice must not be mutated: `bd conflicts show` renders the + // same rows again after filtering for JSON. + if len(rows[0].Fields) != 2 { + t.Error("filterShownFields mutated its input") + } +} + +// The conflict class is what tells an operator what ours/theirs will DO, so +// each combination has to be named correctly. +func TestConflictKind(t *testing.T) { + cases := []struct { + row storage.ConflictRow + want string + }{ + {storage.ConflictRow{BaseExists: true, OurExists: true, TheirExists: true}, "both sides modified"}, + {storage.ConflictRow{OurExists: true, TheirExists: true}, "both sides added"}, + {storage.ConflictRow{BaseExists: true, OurExists: true}, "we modified / they deleted"}, + {storage.ConflictRow{BaseExists: true, TheirExists: true}, "we deleted / they modified"}, + {storage.ConflictRow{BaseExists: true}, "both sides deleted"}, + } + for _, c := range cases { + if got := conflictKind(c.row); got != c.want { + t.Errorf("conflictKind(%+v) = %q, want %q", c.row, got, c.want) + } + } +} + +func TestConflictValueDistinguishesNullFromEmpty(t *testing.T) { + if got := conflictValue(nil); got != "(null)" { + t.Errorf("nil renders as %q, want (null)", got) + } + if got := conflictValue(strp("")); got != `""` { + t.Errorf("empty renders as %q, want \"\"", got) + } + if got := conflictValue(strp("a\nb")); got != `a\nb` { + t.Errorf("newlines must not break the field layout, got %q", got) + } +} diff --git a/internal/storage/dolt/versioned.go b/internal/storage/dolt/versioned.go index 2275af852..dff0ab8c2 100644 --- a/internal/storage/dolt/versioned.go +++ b/internal/storage/dolt/versioned.go @@ -3,6 +3,7 @@ package dolt import ( "context" "database/sql" + "database/sql/driver" "fmt" "time" @@ -98,6 +99,41 @@ func (s *DoltStore) GetConflicts(ctx context.Context) ([]storage.Conflict, error return versioncontrolops.GetConflicts(ctx, s.db) } +// The CLI reaches these two methods through storage.UnwrapStore, so the +// assertion must keep holding on the concrete store. +var _ storage.ConflictInspector = (*DoltStore)(nil) + +// GetConflictRows returns the live conflicted rows of table, per field. +// Implements storage.ConflictInspector (backs `bd conflicts list|show`). +func (s *DoltStore) GetConflictRows(ctx context.Context, table string) ([]storage.ConflictRow, error) { + return versioncontrolops.GetConflictRows(ctx, s.db, table) +} + +// ResolveConflictRows resolves individual conflicted rows of table by key. +// Implements storage.ConflictInspector (backs `bd conflicts resolve `). +// +// It runs on a pinned connection, not the pool: the resolution sets dolt's +// conflict-tolerance session flags, and on *sql.DB a follow-up statement could +// land on a different connection that never saw them. +// The flags it sets are session-scoped, so they are reset before the +// connection goes back to the pool; if the reset fails the connection is +// discarded rather than returned dirty (the discipline +// autoResolveConflictsAfterCLIPull already follows, store.go:3323). +func (s *DoltStore) ResolveConflictRows(ctx context.Context, table string, keys []string, strategy string) (int, error) { + conn, err := s.db.Conn(ctx) + if err != nil { + return 0, fmt.Errorf("acquire connection for conflict resolution: %w", err) + } + defer func() { + if _, err := conn.ExecContext(ctx, + "SET @@dolt_allow_commit_conflicts = 0, @@dolt_force_transaction_commit = 0"); err != nil { + _ = conn.Raw(func(any) error { return driver.ErrBadConn }) + } + _ = conn.Close() + }() + return versioncontrolops.ResolveConflictRows(ctx, conn, table, keys, strategy) +} + // CommitExists checks whether a commit hash exists in the repository. // Returns false for empty strings, malformed input, or non-existent commits. func (s *DoltStore) CommitExists(ctx context.Context, commitHash string) (bool, error) { diff --git a/internal/storage/embeddeddolt/version_control.go b/internal/storage/embeddeddolt/version_control.go index b9206a2e7..d7a353bd4 100644 --- a/internal/storage/embeddeddolt/version_control.go +++ b/internal/storage/embeddeddolt/version_control.go @@ -301,6 +301,36 @@ func (s *EmbeddedDoltStore) ResolveConflicts(ctx context.Context, table string, }) } +// The CLI reaches these two methods through storage.UnwrapStore, so the +// assertion must keep holding on the concrete store. +var _ storage.ConflictInspector = (*EmbeddedDoltStore)(nil) + +// GetConflictRows returns the live conflicted rows of table, per field. +// Implements storage.ConflictInspector (backs `bd conflicts list|show`). +func (s *EmbeddedDoltStore) GetConflictRows(ctx context.Context, table string) ([]storage.ConflictRow, error) { + var rows []storage.ConflictRow + err := s.withDBConn(ctx, func(db versioncontrolops.DBConn) error { + var err error + rows, err = versioncontrolops.GetConflictRows(ctx, db, table) + return err + }) + return rows, err +} + +// ResolveConflictRows resolves individual conflicted rows of table by key. +// Implements storage.ConflictInspector (backs `bd conflicts resolve `). +// It runs on a PINNED connection: the resolution sets dolt's +// conflict-tolerance session flags, which the writes that follow must see. +func (s *EmbeddedDoltStore) ResolveConflictRows(ctx context.Context, table string, keys []string, strategy string) (int, error) { + var n int + err := s.withMutatingPinnedDBConn(ctx, func(db versioncontrolops.DBConn) error { + var err error + n, err = versioncontrolops.ResolveConflictRows(ctx, db, table, keys, strategy) + return err + }) + return n, err +} + // --------------------------------------------------------------------------- // Remote operations // --------------------------------------------------------------------------- diff --git a/internal/storage/version_control.go b/internal/storage/version_control.go index c2ae6e2cb..8f5fbb73a 100644 --- a/internal/storage/version_control.go +++ b/internal/storage/version_control.go @@ -26,6 +26,57 @@ type Status struct { Unstaged []StatusEntry } +// ConflictFieldValue is one column of a conflicted row, presented per side. +// A nil pointer means the side has no value for the field: either the side +// deleted (or never had) the row, or the column itself is NULL there. +type ConflictFieldValue struct { + Name string `json:"name"` + Base *string `json:"base"` + Ours *string `json:"ours"` + Theirs *string `json:"theirs"` +} + +// ConflictRow is one conflicted row of one table, presented as fields rather +// than as the raw base_/our_/their_ column soup of dolt_conflicts_. +type ConflictRow struct { + Table string `json:"table"` + // Key identifies the row: the issue ID for the issues table, and a + // best-effort identifying value for the others. + Key string `json:"key"` + // OurDiffType/TheirDiffType are dolt's own classification of the + // row on each side ("added", "modified", "removed"); empty when the + // conflict table does not carry them. + OurDiffType string `json:"our_diff_type,omitempty"` + TheirDiffType string `json:"their_diff_type,omitempty"` + // BaseExists/OurExists/TheirExists report whether the row is present + // on that side of the merge. A false OurExists or TheirExists is a + // delete/modify conflict; a false BaseExists is an add/add conflict. + BaseExists bool `json:"base_exists"` + OurExists bool `json:"our_exists"` + TheirExists bool `json:"their_exists"` + Fields []ConflictFieldValue `json:"fields"` +} + +// Differs reports whether ours and theirs disagree on this field. +func (f ConflictFieldValue) Differs() bool { + if f.Ours == nil || f.Theirs == nil { + return f.Ours != f.Theirs + } + return *f.Ours != *f.Theirs +} + +// ConflictInspector is the optional, issue-oriented conflict surface behind +// `bd conflicts` (GH federation ask #3). It is implemented by the Dolt-backed +// stores only; callers must type-assert. +type ConflictInspector interface { + // GetConflictRows returns the live conflicted rows of table, per field. + GetConflictRows(ctx context.Context, table string) ([]ConflictRow, error) + // ResolveConflictRows resolves individual conflicted rows of table by + // key (issue ID) with strategy "ours" or "theirs", leaving every other + // conflicted row untouched. It returns the number of rows resolved. + ResolveConflictRows(ctx context.Context, table string, keys []string, strategy string) (int, error) +} + // VersionControl provides branch, commit, merge, and status operations. type VersionControl interface { Branch(ctx context.Context, name string) error diff --git a/internal/storage/versioncontrolops/conflicts.go b/internal/storage/versioncontrolops/conflicts.go new file mode 100644 index 000000000..159a68e73 --- /dev/null +++ b/internal/storage/versioncontrolops/conflicts.go @@ -0,0 +1,398 @@ +package versioncontrolops + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + "github.com/steveyegge/beads/internal/storage" +) + +// This file backs `bd conflicts` (federation ask #3): the issue-oriented view +// of a halted merge that spares operators the raw dolt CLI +// (`dolt conflicts cat`, `dolt conflicts resolve`, `dolt add -A && dolt +// commit`). It reads dolt's per-table conflict tables — dolt_conflicts_, +// whose columns are base_/our_/their_plus the +// our_diff_type/their_diff_type metadata — and re-presents them as one row per +// conflicted issue with its fields side by side. +// +// It is deliberately generic over tables (issues, dependencies, config, +// comments, …): the column split is derived from the result-set column names, +// not from a hardcoded schema that would rot on the next migration. + +// ConflictStrategyOurs / ConflictStrategyTheirs are the two resolution +// strategies, matching `dolt conflicts resolve --ours|--theirs`. +const ( + ConflictStrategyOurs = "ours" + ConflictStrategyTheirs = "theirs" +) + +// conflictSides are dolt's conflict-column prefixes. No prefix is a prefix of +// another, so a column is split by at most one of them and a field named e.g. +// "their_thing" survives as our_their_thing -> (our, their_thing). +var conflictSides = []string{"base_", "our_", "their_"} + +// conflictMetaSuffixes are conflict-table columns that describe the conflict +// rather than the row's data: dolt adds our_diff_type/their_diff_type always, +// and base_cardinality/our_cardinality/their_cardinality for keyless tables. +var conflictMetaSuffixes = map[string]bool{ + "diff_type": true, + "cardinality": true, +} + +// conflictRowKeyColumn maps a table to the column that identifies a row for +// per-row resolution. Only tables listed here support resolving individual +// rows; everything else is resolvable table-wide (DOLT_CONFLICTS_RESOLVE), +// which is what dolt itself offers. +var conflictRowKeyColumn = map[string]string{ + "issues": "id", +} + +// ValidateConflictTable rejects anything that is not a plain SQL identifier, +// so a table name can be safely interpolated into a conflict query. Conflict +// table names come from dolt_conflicts (or an operator's --table) and MySQL +// cannot parameterize an identifier, so they are validated instead. It reuses +// the package's existing table-name gate, which ResolveConflicts already +// trusts for exactly this. +func ValidateConflictTable(table string) error { + return validateTableName(table) +} + +// ValidateConflictStrategy accepts only the two dolt strategies. +func ValidateConflictStrategy(strategy string) error { + switch strategy { + case ConflictStrategyOurs, ConflictStrategyTheirs: + return nil + default: + return fmt.Errorf("invalid strategy %q (want %q or %q)", strategy, ConflictStrategyOurs, ConflictStrategyTheirs) + } +} + +// SupportsRowResolve reports whether table can be resolved row by row. +func SupportsRowResolve(table string) bool { + _, ok := conflictRowKeyColumn[table] + return ok +} + +// splitConflictColumn splits a dolt conflict column into its side and field +// name. ok is false for columns that belong to no side (dolt does not emit +// any today, but a future column must not be silently treated as a field). +func splitConflictColumn(col string) (side, field string, ok bool) { + for _, s := range conflictSides { + if strings.HasPrefix(col, s) { + return strings.TrimSuffix(s, "_"), strings.TrimPrefix(col, s), true + } + } + return "", "", false +} + +// formatConflictValue renders a scanned SQL value for display. A NULL becomes +// a nil pointer — distinct from the empty string, which is a real value. +func formatConflictValue(v any) *string { + if v == nil { + return nil + } + var s string + switch t := v.(type) { + case []byte: + s = string(t) + case string: + s = t + case time.Time: + s = t.UTC().Format(time.RFC3339) + default: + s = fmt.Sprint(t) + } + return &s +} + +// GetConflictRows returns the live conflicted rows of table, one entry per +// conflicted row with its columns presented per field. It reads the working +// set: a merge whose conflicts were aborted (the auto-settle path) leaves +// nothing here, which is correct — those conflicts no longer exist. +func GetConflictRows(ctx context.Context, db DBConn, table string) ([]storage.ConflictRow, error) { + if err := ValidateConflictTable(table); err != nil { + return nil, err + } + rows, err := db.QueryContext(ctx, "SELECT * FROM `dolt_conflicts_"+table+"`") //nolint:gosec // table validated as an identifier above + if err != nil { + return nil, fmt.Errorf("query conflicts for table %s: %w", table, err) + } + defer func() { _ = rows.Close() }() + + cols, err := rows.Columns() + if err != nil { + return nil, fmt.Errorf("conflict columns for table %s: %w", table, err) + } + + var out []storage.ConflictRow + for rows.Next() { + vals := make([]any, len(cols)) + ptrs := make([]any, len(cols)) + for i := range vals { + ptrs[i] = &vals[i] + } + if err := rows.Scan(ptrs...); err != nil { + return nil, fmt.Errorf("scan conflict row for table %s: %w", table, err) + } + out = append(out, buildConflictRow(table, cols, vals)) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("iterate conflicts for table %s: %w", table, err) + } + return out, nil +} + +// buildConflictRow re-presents one raw conflict row as fields. It is pure, so +// the column-splitting rules are unit-testable without a database. +func buildConflictRow(table string, cols []string, vals []any) storage.ConflictRow { + row := storage.ConflictRow{Table: table} + index := make(map[string]int, len(cols)) + for i, col := range cols { + side, field, ok := splitConflictColumn(col) + if !ok { + continue + } + v := formatConflictValue(vals[i]) + if conflictMetaSuffixes[field] { + if field == "diff_type" && v != nil { + switch side { + case "our": + row.OurDiffType = *v + case "their": + row.TheirDiffType = *v + } + } + continue + } + pos, seen := index[field] + if !seen { + pos = len(row.Fields) + index[field] = pos + row.Fields = append(row.Fields, storage.ConflictFieldValue{Name: field}) + } + switch side { + case "base": + row.Fields[pos].Base = v + case "our": + row.Fields[pos].Ours = v + case "their": + row.Fields[pos].Theirs = v + } + if v != nil { + switch side { + case "base": + row.BaseExists = true + case "our": + row.OurExists = true + case "their": + row.TheirExists = true + } + } + } + row.Key = conflictRowKey(table, row.Fields) + return row +} + +// conflictRowKey picks the value that identifies a conflicted row: the table's +// key column when it has one (issues.id), else the first field carrying any +// value. Presentation only — resolution keys off conflictRowKeyColumn. +func conflictRowKey(table string, fields []storage.ConflictFieldValue) string { + keyCol, hasKey := conflictRowKeyColumn[table] + for _, f := range fields { + if hasKey && f.Name != keyCol { + continue + } + for _, v := range []*string{f.Ours, f.Theirs, f.Base} { + if v != nil { + return *v + } + } + if hasKey { + return "" + } + } + return "" +} + +// ResolveConflictRows resolves the named rows of table with strategy, +// leaving every other conflicted row of that table conflicted. Only tables in +// conflictRowKeyColumn support it, and only modify/modify rows (present on +// both sides): a delete/modify or add/add row is refused by name rather than +// guessed at, because "ours" and "theirs" do not describe what the operator +// wants when one side deleted the row. +// +// db must be a SINGLE session (a pinned *sql.Conn, or a *sql.Tx): the +// conflict-tolerance flags set here have to be visible to the writes that +// follow, and dolt refuses to commit a transaction touching a table with live +// conflicts without them. +func ResolveConflictRows(ctx context.Context, db DBConn, table string, keys []string, strategy string) (int, error) { + if err := ValidateConflictTable(table); err != nil { + return 0, err + } + if err := ValidateConflictStrategy(strategy); err != nil { + return 0, err + } + keyCol, ok := conflictRowKeyColumn[table] + if !ok { + return 0, fmt.Errorf("per-row conflict resolution is not supported for table %s; resolve the whole table instead", table) + } + if len(keys) == 0 { + return 0, nil + } + // A conflicted table cannot be written — nor the session committed — + // without dolt's conflict-tolerance flags (the same pair MergeAndSettle + // sets). They are session state, which is why db must be one session. + if _, err := db.ExecContext(ctx, "SET @@dolt_allow_commit_conflicts = 1"); err != nil { + return 0, fmt.Errorf("set dolt_allow_commit_conflicts: %w", err) + } + if _, err := db.ExecContext(ctx, "SET @@dolt_force_transaction_commit = 1"); err != nil { + return 0, fmt.Errorf("set dolt_force_transaction_commit: %w", err) + } + + resolved := 0 + for _, key := range keys { + row, err := loadConflictRow(ctx, db, table, keyCol, key) + if err != nil { + return resolved, err + } + if err := resolveOneConflictRow(ctx, db, table, keyCol, key, strategy, row); err != nil { + return resolved, err + } + resolved++ + } + return resolved, nil +} + +// rawConflictRow is one conflict row kept in raw scanned form, so their_* +// values can be written straight back into the base table. +type rawConflictRow struct { + cols []string + vals []any +} + +// value returns the raw value of side_field, and whether the column exists. +func (r rawConflictRow) value(side, field string) (any, bool) { + want := side + "_" + field + for i, c := range r.cols { + if c == want { + return r.vals[i], true + } + } + return nil, false +} + +// theirFields returns their_* data columns (metadata and the key column +// excluded) in conflict-table order. +func (r rawConflictRow) theirFields(keyCol string) (names []string, vals []any) { + for i, c := range r.cols { + side, field, ok := splitConflictColumn(c) + if !ok || side != "their" || conflictMetaSuffixes[field] || field == keyCol { + continue + } + names = append(names, field) + vals = append(vals, r.vals[i]) + } + return names, vals +} + +// loadConflictRow fetches the single conflict row for key. It matches on +// either side's key column so a row only one side has is *found* and then +// refused with a precise message, rather than reported as "no conflict". +func loadConflictRow(ctx context.Context, db DBConn, table, keyCol, key string) (rawConflictRow, error) { + q := fmt.Sprintf("SELECT * FROM `dolt_conflicts_%s` WHERE `our_%s` = ? OR `their_%s` = ?", table, keyCol, keyCol) //nolint:gosec // identifiers validated + rows, err := db.QueryContext(ctx, q, key, key) + if err != nil { + return rawConflictRow{}, fmt.Errorf("query conflict for %s %s: %w", table, key, err) + } + defer func() { _ = rows.Close() }() + + cols, err := rows.Columns() + if err != nil { + return rawConflictRow{}, fmt.Errorf("conflict columns for table %s: %w", table, err) + } + if !rows.Next() { + if err := rows.Err(); err != nil { + return rawConflictRow{}, fmt.Errorf("query conflict for %s %s: %w", table, key, err) + } + return rawConflictRow{}, fmt.Errorf("no live conflict for %s %s", table, key) + } + vals := make([]any, len(cols)) + ptrs := make([]any, len(cols)) + for i := range vals { + ptrs[i] = &vals[i] + } + if err := rows.Scan(ptrs...); err != nil { + return rawConflictRow{}, fmt.Errorf("scan conflict for %s %s: %w", table, key, err) + } + if rows.Next() { + return rawConflictRow{}, fmt.Errorf("multiple conflict rows for %s %s; resolve the whole table instead", table, key) + } + return rawConflictRow{cols: cols, vals: vals}, errors.Join(rows.Err(), rows.Close()) +} + +// resolveOneConflictRow applies strategy to a single modify/modify row. +// +// "ours" is dolt's manual-resolution path: the working set already holds our +// values, so deleting the conflict row *is* the resolution. "theirs" first +// writes their values over ours, then deletes the conflict row — the order +// matters, since the delete is what tells dolt the row is settled. +func resolveOneConflictRow(ctx context.Context, db DBConn, table, keyCol, key, strategy string, row rawConflictRow) error { + ourKey, ourOK := row.value("our", keyCol) + theirKey, theirOK := row.value("their", keyCol) + if !ourOK || !theirOK { + return fmt.Errorf("conflict table dolt_conflicts_%s has no our_%s/their_%s column", table, keyCol, keyCol) + } + if ourKey == nil || theirKey == nil { + // delete/modify (one side removed the row) or add/add against a + // missing key: refuse by name. Row-level ours/theirs would silently + // resurrect or destroy a row the operator never looked at. + return fmt.Errorf("conflict for %s %s is not a modify/modify conflict (one side has no row); "+ + "resolve it with a whole-table strategy or edit the row directly", table, key) + } + + if strategy == ConflictStrategyTheirs { + names, vals := row.theirFields(keyCol) + if len(names) == 0 { + return fmt.Errorf("conflict for %s %s carries no their_* data columns", table, key) + } + sets := make([]string, len(names)) + args := make([]any, 0, len(names)+1) + for i, n := range names { + // Column names are interpolated (MySQL cannot bind an + // identifier) and come from the conflict table's own schema, + // which a peer's schema merge can extend — gate them exactly + // like the table name rather than trusting the source. + if err := ValidateConflictTable(n); err != nil { + return fmt.Errorf("refusing to write unexpected column %q of %s: %w", n, table, err) + } + sets[i] = fmt.Sprintf("`%s` = ?", n) + args = append(args, vals[i]) + } + args = append(args, ourKey) + stmt := fmt.Sprintf("UPDATE `%s` SET %s WHERE `%s` = ?", table, strings.Join(sets, ", "), keyCol) //nolint:gosec // identifiers validated above + res, err := db.ExecContext(ctx, stmt, args...) + if err != nil { + return fmt.Errorf("apply their values for %s %s: %w", table, key, err) + } + // Zero rows means the row we read the conflict for is no longer + // there — another session on the same branch deleted it between the + // read and the write. Clearing the conflict now would discard their + // side under a --theirs invocation, undetectably. Stop instead. + if n, err := res.RowsAffected(); err == nil && n == 0 { + return fmt.Errorf("their values for %s %s matched no row (was it deleted concurrently?); conflict left unresolved", table, key) + } + } + + del := fmt.Sprintf("DELETE FROM `dolt_conflicts_%s` WHERE `our_%s` = ?", table, keyCol) //nolint:gosec // identifiers validated + res, err := db.ExecContext(ctx, del, ourKey) + if err != nil { + return fmt.Errorf("clear conflict for %s %s: %w", table, key, err) + } + if n, err := res.RowsAffected(); err == nil && n == 0 { + return fmt.Errorf("conflict for %s %s was not cleared (no conflict row deleted)", table, key) + } + return nil +} diff --git a/internal/storage/versioncontrolops/conflicts_test.go b/internal/storage/versioncontrolops/conflicts_test.go new file mode 100644 index 000000000..a12baf7c9 --- /dev/null +++ b/internal/storage/versioncontrolops/conflicts_test.go @@ -0,0 +1,205 @@ +package versioncontrolops + +import ( + "testing" + "time" +) + +func TestSplitConflictColumn(t *testing.T) { + cases := []struct { + col string + side string + field string + ok bool + }{ + {"base_id", "base", "id", true}, + {"our_updated_at", "our", "updated_at", true}, + {"their_diff_type", "their", "diff_type", true}, + {"our_their_thing", "our", "their_thing", true}, + {"dolt_row_hash", "", "", false}, + } + for _, c := range cases { + side, field, ok := splitConflictColumn(c.col) + if side != c.side || field != c.field || ok != c.ok { + t.Errorf("splitConflictColumn(%q) = (%q,%q,%v), want (%q,%q,%v)", + c.col, side, field, ok, c.side, c.field, c.ok) + } + } +} + +func TestFormatConflictValue(t *testing.T) { + if got := formatConflictValue(nil); got != nil { + t.Errorf("NULL should format as a nil pointer, got %q", *got) + } + if got := formatConflictValue([]byte("")); got == nil || *got != "" { + t.Errorf("empty string must stay distinct from NULL, got %v", got) + } + ts := time.Date(2026, 7, 25, 1, 2, 3, 0, time.UTC) + if got := formatConflictValue(ts); got == nil || *got != "2026-07-25T01:02:03Z" { + t.Errorf("time formatting = %v, want RFC3339 UTC", got) + } + if got := formatConflictValue(int64(7)); got == nil || *got != "7" { + t.Errorf("int formatting = %v, want \"7\"", got) + } +} + +// buildConflictRow is the whole presentation contract: fold base_/our_/their_ +// columns into one field each, keep the metadata out of the field list, and +// classify which sides have the row. +func TestBuildConflictRowModifyModify(t *testing.T) { + cols := []string{ + "base_id", "our_id", "their_id", + "base_status", "our_status", "their_status", + "base_title", "our_title", "their_title", + "our_diff_type", "their_diff_type", + } + vals := []any{ + []byte("bd-1"), []byte("bd-1"), []byte("bd-1"), + []byte("open"), []byte("in_progress"), []byte("closed"), + []byte("t"), []byte("t"), []byte("t"), + []byte("modified"), []byte("modified"), + } + row := buildConflictRow("issues", cols, vals) + + if row.Key != "bd-1" { + t.Errorf("Key = %q, want bd-1", row.Key) + } + if !row.BaseExists || !row.OurExists || !row.TheirExists { + t.Errorf("modify/modify should exist on all sides, got base=%v our=%v their=%v", + row.BaseExists, row.OurExists, row.TheirExists) + } + if row.OurDiffType != "modified" || row.TheirDiffType != "modified" { + t.Errorf("diff types = %q/%q, want modified/modified", row.OurDiffType, row.TheirDiffType) + } + if len(row.Fields) != 3 { + t.Fatalf("want 3 fields (id,status,title), got %d: %+v", len(row.Fields), row.Fields) + } + byName := map[string]int{} + for i, f := range row.Fields { + byName[f.Name] = i + } + for _, meta := range []string{"diff_type", "cardinality"} { + if _, ok := byName[meta]; ok { + t.Errorf("%s is conflict metadata and must not appear as a field", meta) + } + } + status := row.Fields[byName["status"]] + if status.Base == nil || *status.Base != "open" || status.Ours == nil || *status.Ours != "in_progress" || status.Theirs == nil || *status.Theirs != "closed" { + t.Errorf("status field = %+v, want base=open ours=in_progress theirs=closed", status) + } + if !status.Differs() { + t.Error("status diverged and must report Differs") + } + if row.Fields[byName["title"]].Differs() { + t.Error("title agrees on both sides and must not report Differs") + } +} + +func TestBuildConflictRowDeleteModify(t *testing.T) { + cols := []string{ + "base_id", "our_id", "their_id", + "base_status", "our_status", "their_status", + "our_diff_type", "their_diff_type", + } + // They deleted the row: every their_* column is NULL. + vals := []any{ + []byte("bd-2"), []byte("bd-2"), nil, + []byte("open"), []byte("closed"), nil, + []byte("modified"), []byte("removed"), + } + row := buildConflictRow("issues", cols, vals) + + if row.Key != "bd-2" { + t.Errorf("Key = %q, want bd-2 (our side still has it)", row.Key) + } + if !row.OurExists || row.TheirExists { + t.Errorf("want our=true their=false, got our=%v their=%v", row.OurExists, row.TheirExists) + } + status := row.Fields[1] + if status.Theirs != nil { + t.Errorf("their status should be nil on a deleted side, got %q", *status.Theirs) + } + if !status.Differs() { + t.Error("a present-vs-absent value must count as differing") + } +} + +// A table with no registered key column still has to render, so `bd conflicts +// show` works for dependencies/config rows the resolver could not settle. +func TestConflictRowKeyFallbackForUnkeyedTable(t *testing.T) { + cols := []string{"base_key", "our_key", "their_key", "base_value", "our_value", "their_value"} + vals := []any{nil, nil, []byte("kv.memory.x"), nil, nil, []byte("v")} + row := buildConflictRow("config", cols, vals) + if row.Key != "kv.memory.x" { + t.Errorf("Key = %q, want the first field carrying a value", row.Key) + } + if row.BaseExists || row.OurExists || !row.TheirExists { + t.Errorf("their-side-only add misclassified: base=%v our=%v their=%v", + row.BaseExists, row.OurExists, row.TheirExists) + } +} + +func TestTheirFieldsExcludesKeyAndMetadata(t *testing.T) { + raw := rawConflictRow{ + cols: []string{"base_id", "our_id", "their_id", "our_status", "their_status", "their_diff_type", "their_cardinality"}, + vals: []any{[]byte("bd-1"), []byte("bd-1"), []byte("bd-1"), []byte("open"), []byte("closed"), []byte("modified"), int64(1)}, + } + names, vals := raw.theirFields("id") + if len(names) != 1 || names[0] != "status" { + t.Fatalf("theirFields = %v, want only [status] (key and metadata excluded)", names) + } + if s, ok := vals[0].([]byte); !ok || string(s) != "closed" { + t.Errorf("their status value = %v, want closed", vals[0]) + } +} + +func TestRawConflictRowValue(t *testing.T) { + raw := rawConflictRow{cols: []string{"our_id", "their_id"}, vals: []any{[]byte("bd-1"), nil}} + if v, ok := raw.value("our", "id"); !ok || string(v.([]byte)) != "bd-1" { + t.Errorf("our_id = %v (ok=%v), want bd-1", v, ok) + } + if v, ok := raw.value("their", "id"); !ok || v != nil { + t.Errorf("their_id = %v (ok=%v), want a present-but-NULL column", v, ok) + } + if _, ok := raw.value("base", "id"); ok { + t.Error("base_id is absent and must report ok=false") + } +} + +func TestValidateConflictTableRejectsInjection(t *testing.T) { + // Table names are interpolated (MySQL cannot bind an identifier), so the + // gate is the only thing between an operator's --table and the query. + for _, bad := range []string{"", "issues; DROP TABLE issues", "issues`", "iss ues", "../etc"} { + if err := ValidateConflictTable(bad); err == nil { + t.Errorf("ValidateConflictTable(%q) = nil, want an error", bad) + } + } + for _, good := range []string{"issues", "dependencies", "schema_migrations"} { + if err := ValidateConflictTable(good); err != nil { + t.Errorf("ValidateConflictTable(%q) = %v, want nil", good, err) + } + } +} + +func TestValidateConflictStrategy(t *testing.T) { + if err := ValidateConflictStrategy("ours"); err != nil { + t.Errorf("ours rejected: %v", err) + } + if err := ValidateConflictStrategy("theirs"); err != nil { + t.Errorf("theirs rejected: %v", err) + } + for _, bad := range []string{"", "OURS", "mine", "--ours"} { + if err := ValidateConflictStrategy(bad); err == nil { + t.Errorf("ValidateConflictStrategy(%q) = nil, want an error", bad) + } + } +} + +func TestSupportsRowResolve(t *testing.T) { + if !SupportsRowResolve("issues") { + t.Error("issues must support per-row resolution") + } + if SupportsRowResolve("dependencies") { + t.Error("only tables with a registered key column may claim per-row resolution") + } +} diff --git a/internal/storage/versioncontrolops/version_control.go b/internal/storage/versioncontrolops/version_control.go index 11f12cf8e..57336f7e8 100644 --- a/internal/storage/versioncontrolops/version_control.go +++ b/internal/storage/versioncontrolops/version_control.go @@ -123,8 +123,8 @@ func GetConflicts(ctx context.Context, db DBConn) ([]storage.Conflict, error) { } conflicts = append(conflicts, storage.Conflict{ Field: tableName, + Count: numConflicts, }) - _ = numConflicts // available if needed in the future } return conflicts, rows.Err() } diff --git a/internal/storage/versioned.go b/internal/storage/versioned.go index 5299f2a40..5722df688 100644 --- a/internal/storage/versioned.go +++ b/internal/storage/versioned.go @@ -29,6 +29,10 @@ type Conflict struct { Field string // Which field has the conflict (empty for table-level) OursValue interface{} // Value on current branch TheirsValue interface{} // Value on merged branch + // Count is how many rows of the table are conflicted, as reported by + // dolt_conflicts.num_conflicts. Meaningful for table-level conflicts + // (the shape GetConflicts returns); zero otherwise. + Count int } // RemoteInfo describes a configured remote.