| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "errors" |
| 7 | "net/url" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | |
| 11 | "amadan.net/oficina/alta/provision" |
| 12 | "modernc.org/sqlite" |
| 13 | ) |
| 14 | |
| 15 | // snapshot answers an in-memory copy of the state at path, for a run |
| 16 | // that must not write. The source is opened read-only (mode=ro) and |
| 17 | // copied by SQLite's online backup in a single step, which holds one read |
| 18 | // transaction for the whole copy: the result is one committed state, WAL |
| 19 | // contents included, whatever another connection commits or checkpoints |
| 20 | // meanwhile. Nothing is copied to disk; the only files SQLite may touch |
| 21 | // are its own -shm and -wal coordination files, never the committed |
| 22 | // contents. With no state at path, the snapshot is an empty database. |
| 23 | func snapshot(ctx context.Context, path string) (*sql.DB, error) { |
| 24 | mem, err := provision.OpenDB(":memory:") |
| 25 | if err != nil { |
| 26 | return nil, err |
| 27 | } |
| 28 | if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) { |
| 29 | return mem, nil |
| 30 | } |
| 31 | if err := restore(ctx, mem, path); err != nil { |
| 32 | mem.Close() |
| 33 | return nil, err |
| 34 | } |
| 35 | return mem, nil |
| 36 | } |
| 37 | |
| 38 | // readOnly is path as a read-only SQLite URI, waiting out a writer's |
| 39 | // brief lock rather than failing. |
| 40 | func readOnly(path string) (string, error) { |
| 41 | abs, err := filepath.Abs(path) |
| 42 | if err != nil { |
| 43 | return "", err |
| 44 | } |
| 45 | return (&url.URL{Scheme: "file", Path: abs, RawQuery: "mode=ro&_pragma=busy_timeout(5000)"}).String(), nil |
| 46 | } |
| 47 | |
| 48 | func restore(ctx context.Context, mem *sql.DB, path string) error { |
| 49 | src, err := readOnly(path) |
| 50 | if err != nil { |
| 51 | return err |
| 52 | } |
| 53 | conn, err := mem.Conn(ctx) |
| 54 | if err != nil { |
| 55 | return err |
| 56 | } |
| 57 | defer conn.Close() |
| 58 | return conn.Raw(func(dc any) error { |
| 59 | r, ok := dc.(interface { |
| 60 | NewRestore(string) (*sqlite.Backup, error) |
| 61 | }) |
| 62 | if !ok { |
| 63 | return errors.New("alta-adopt: the SQLite driver cannot restore") |
| 64 | } |
| 65 | b, err := r.NewRestore(src) |
| 66 | if err != nil { |
| 67 | return err |
| 68 | } |
| 69 | // -1: every page in one step, so one read transaction. |
| 70 | more, err := b.Step(-1) |
| 71 | if ferr := b.Finish(); err == nil { |
| 72 | err = ferr |
| 73 | } |
| 74 | if err == nil && more { |
| 75 | err = errors.New("alta-adopt: the snapshot did not finish in one step") |
| 76 | } |
| 77 | return err |
| 78 | }) |
| 79 | } |
| 80 | |