package main import ( "context" "database/sql" "errors" "net/url" "os" "path/filepath" "amadan.net/oficina/alta/provision" "modernc.org/sqlite" ) // snapshot answers an in-memory copy of the state at path, for a run // that must not write. The source is opened read-only (mode=ro) and // copied by SQLite's online backup in a single step, which holds one read // transaction for the whole copy: the result is one committed state, WAL // contents included, whatever another connection commits or checkpoints // meanwhile. Nothing is copied to disk; the only files SQLite may touch // are its own -shm and -wal coordination files, never the committed // contents. With no state at path, the snapshot is an empty database. func snapshot(ctx context.Context, path string) (*sql.DB, error) { mem, err := provision.OpenDB(":memory:") if err != nil { return nil, err } if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) { return mem, nil } if err := restore(ctx, mem, path); err != nil { mem.Close() return nil, err } return mem, nil } // readOnly is path as a read-only SQLite URI, waiting out a writer's // brief lock rather than failing. func readOnly(path string) (string, error) { abs, err := filepath.Abs(path) if err != nil { return "", err } return (&url.URL{Scheme: "file", Path: abs, RawQuery: "mode=ro&_pragma=busy_timeout(5000)"}).String(), nil } func restore(ctx context.Context, mem *sql.DB, path string) error { src, err := readOnly(path) if err != nil { return err } conn, err := mem.Conn(ctx) if err != nil { return err } defer conn.Close() return conn.Raw(func(dc any) error { r, ok := dc.(interface { NewRestore(string) (*sqlite.Backup, error) }) if !ok { return errors.New("alta-adopt: the SQLite driver cannot restore") } b, err := r.NewRestore(src) if err != nil { return err } // -1: every page in one step, so one read transaction. more, err := b.Step(-1) if ferr := b.Finish(); err == nil { err = ferr } if err == nil && more { err = errors.New("alta-adopt: the snapshot did not finish in one step") } return err }) }