package dbcopy import ( "errors" "os" "path/filepath" "strings" "testing" "gorm.io/driver/sqlite" "gorm.io/gorm" "gorm.io/gorm/logger" ) // walFile makes a sqlite file in WAL mode with one table and returns its // path and an open writer that keeps the WAL from being checkpointed func walFile(t *testing.T) (string, *gorm.DB) { t.Helper() path := filepath.Join(t.TempDir(), "source.db") w, err := gorm.Open(sqlite.Open("file:"+path+"?_journal_mode=WAL"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) if err != nil { t.Fatal(err) } sqlDB, err := w.DB() if err != nil { t.Fatal(err) } sqlDB.SetMaxOpenConns(1) t.Cleanup(func() { _ = sqlDB.Close() }) for _, stmt := range []string{ "PRAGMA wal_autocheckpoint = 0", "CREATE TABLE notes (body text)", "INSERT INTO notes VALUES ('one')", } { if err := w.Exec(stmt).Error; err != nil { t.Fatal(err) } } return path, w } // TestOpenSourceReadOnly checks that no DSN opens the source writable or // makes a file: a # or NUL is refused before sqlite sees it, operator // parameters are dropped, and a source with a WAL that is not checkpointed // is read without a change to the database or the WAL file func TestOpenSourceReadOnly(t *testing.T) { dir := t.TempDir() missing := filepath.Join(dir, "missing.db") for _, dsn := range []string{ missing, "file:" + missing, "file:" + missing + "?cache=private#", "file:" + missing + "?mode=rwc", missing + "\x00", "file:" + missing + "%00", } { if db, err := OpenSource(dsn); err == nil { closeDB(t, db) t.Errorf("%q: a missing file opened", dsn) } if _, err := os.Stat(missing); !errors.Is(err, os.ErrNotExist) { t.Fatalf("%q: the missing file was made", dsn) } } path, w := walFile(t) if err := w.Exec("INSERT INTO notes VALUES ('two')").Error; err != nil { t.Fatal(err) } if _, err := os.Stat(path + "-wal"); err != nil { t.Fatalf("no WAL file: %v", err) } mainBefore := fileSum(t, path) walBefore := fileSum(t, path+"-wal") for _, dsn := range []string{"file:" + path + "?cache=private#", "file:" + path + "\x00"} { if db, err := OpenSource(dsn); err == nil { closeDB(t, db) t.Errorf("%q opened", dsn) } } for _, dsn := range []string{path, "file:" + path + "?mode=rwc&_txlock=immediate"} { src, err := OpenSource(dsn) if err != nil { t.Fatalf("%q: %v", dsn, err) } var n int64 if err := src.Raw("SELECT COUNT(*) FROM notes").Scan(&n).Error; err != nil || n != 2 { t.Fatalf("%q: read %d rows, %v; the rows in the WAL must be read", dsn, n, err) } if err := src.Exec("INSERT INTO notes VALUES ('three')").Error; err == nil { t.Fatalf("%q: the source accepted a write", dsn) } closeDB(t, src) } if fileSum(t, path) != mainBefore || fileSum(t, path+"-wal") != walBefore { t.Fatal("the source files changed") } } // TestReadOnlyDSN checks the source DSN becomes a read only file: URI of // the absolute path, with only the parameters of the copy func TestReadOnlyDSN(t *testing.T) { wd, err := os.Getwd() if err != nil { t.Fatal(err) } abs := func(p string) string { return "file:" + filepath.Join(wd, p) + "?mode=ro&_query_only=true" } cases := []struct { in, want string err bool }{ {"file:./db.sqlite3", abs("db.sqlite3"), false}, {"./db.sqlite3", abs("db.sqlite3"), false}, {"/opt/phishingclub/data/db.sqlite3", "file:/opt/phishingclub/data/db.sqlite3?mode=ro&_query_only=true", false}, {"file:///opt/pc/db.sqlite3", "file:/opt/pc/db.sqlite3?mode=ro&_query_only=true", false}, {"file://localhost/opt/pc/db.sqlite3", "file:/opt/pc/db.sqlite3?mode=ro&_query_only=true", false}, {"file:db.sqlite3?_loc=auto", abs("db.sqlite3"), false}, {"file:db.sqlite3?mode=rwc&vfs=unix-none&immutable=1&nolock=1", abs("db.sqlite3"), false}, {"file:/data/a%20b%23c.db", "file:/data/a b%23c.db?mode=ro&_query_only=true", false}, {"file:/data/100%25.db", "file:/data/100%25.db?mode=ro&_query_only=true", false}, {"file://otherhost/db.sqlite3", "", true}, {"db.sqlite3?mode=rwc", "", true}, {"data/a%20b.db", "", true}, {"file:db.sqlite3?cache=private#", "", true}, {"file:db.sqlite3#?mode=rw", "", true}, {"db#.sqlite3", "", true}, {"file:db.sqlite3\x00", "", true}, {"file:db.sqlite3%00x", "", true}, {"db\n.sqlite3", "", true}, {"file::memory:", "", true}, {"file:x?mode=memory", "", true}, {"", "", true}, {"file:?mode=ro", "", true}, } for _, tc := range cases { got, err := readOnlyDSN(tc.in) if (err != nil) != tc.err { t.Errorf("%q: error %v", tc.in, err) continue } if err != nil { if !errors.Is(err, ErrSourceDSN) || strings.Contains(err.Error(), "\x00") { t.Errorf("%q: %v", tc.in, err) } continue } if got != tc.want { t.Errorf("%q: %q, want %q", tc.in, got, tc.want) } } }