diff --git a/CHANGELOG.md b/CHANGELOG.md index c50cb90..3128447 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- Preserve whitespace in FTS table names during optimization so a similarly named table is not modified instead. + - Keep scoped mirror commits limited to literal file and directory selections, so bracketed filenames do not include matching neighboring files. - Preserve whitespace in selected mirror commit paths so a similarly named file is not committed instead. diff --git a/store/fts.go b/store/fts.go index 9c2a465..92a683f 100644 --- a/store/fts.go +++ b/store/fts.go @@ -63,8 +63,7 @@ type contextExecer interface { } func OptimizeFTS5(ctx context.Context, db contextExecer, table string) error { - table = strings.TrimSpace(table) - if table == "" || strings.ContainsAny(table, "\"\x00") { + if strings.TrimSpace(table) == "" || strings.ContainsAny(table, "\"\x00") { return fmt.Errorf("invalid FTS5 table %q", table) } quoted := QuoteIdent(table) diff --git a/store/store_test.go b/store/store_test.go index ab7d7aa..1e9aeab 100644 --- a/store/store_test.go +++ b/store/store_test.go @@ -446,8 +446,43 @@ func TestFTS5Helpers(t *testing.T) { if err := OptimizeFTS5(ctx, st.DB(), "docs"); err != nil { t.Fatal(err) } - if err := OptimizeFTS5(ctx, st.DB(), `bad"table`); err == nil { - t.Fatal("unsafe FTS table should fail") + for _, table := range []string{`bad"table`, "", " \t\n", "bad\x00table"} { + if err := OptimizeFTS5(ctx, st.DB(), table); err == nil { + t.Errorf("unsafe FTS table %q should fail", table) + } + } +} + +func TestOptimizeFTS5PreservesTableName(t *testing.T) { + for _, name := range []string{" docs", "docs ", " docs "} { + t.Run(name, func(t *testing.T) { + ctx := context.Background() + st, err := Open(ctx, Options{Path: filepath.Join(t.TempDir(), "archive.db")}) + if err != nil { + t.Fatal(err) + } + defer st.Close() + if _, err := st.DB().ExecContext(ctx, `create virtual table `+QuoteIdent(name)+` using fts5(body); + create table docs(docs text);`); err != nil { + t.Fatal(err) + } + if err := OptimizeFTS5(ctx, st.DB(), name); err != nil { + t.Fatal(err) + } + var count int + if err := st.DB().QueryRowContext(ctx, `select count(*) from docs`).Scan(&count); err != nil { + t.Fatal(err) + } + if count != 0 { + t.Fatalf("optimization wrote %d rows to the unrelated docs table", count) + } + if _, err := st.DB().ExecContext(ctx, `drop table docs`); err != nil { + t.Fatal(err) + } + if err := OptimizeFTS5(ctx, st.DB(), name); err != nil { + t.Fatalf("optimize literal FTS table without neighbor: %v", err) + } + }) } }