| 1 | package projectiondb |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "fmt" |
| 7 | ) |
| 8 | |
| 9 | // Close the staging writer before publication. Cancellation retains resumable |
| 10 | // progress; failures discard it without changing the currently readable file. |
| 11 | func populateRebuildReplacement(ctx context.Context, opts OpenOptions, handle *Handle, populate func(context.Context, *sql.DB) error, cleanupTemporary func()) error { |
| 12 | if populate != nil { |
| 13 | if err := populate(ctx, handle.DB); err != nil { |
| 14 | _ = handle.DB.Close() |
| 15 | if opts.ResumeKey == "" || ctx.Err() == nil { |
| 16 | cleanupTemporary() |
| 17 | } |
| 18 | return fmt.Errorf("populate projection replacement: %w", err) |
| 19 | } |
| 20 | } |
| 21 | check := `PRAGMA integrity_check` |
| 22 | if opts.QuickCheck { |
| 23 | check = `PRAGMA quick_check(1)` |
| 24 | } |
| 25 | var integrity string |
| 26 | if err := handle.DB.QueryRowContext(ctx, check).Scan(&integrity); err != nil || integrity != "ok" { |
| 27 | _ = handle.DB.Close() |
| 28 | if opts.ResumeKey == "" || ctx.Err() == nil { |
| 29 | cleanupTemporary() |
| 30 | } |
| 31 | if err != nil { |
| 32 | return fmt.Errorf("validate projection replacement: %w", err) |
| 33 | } |
| 34 | return fmt.Errorf("validate projection replacement: %s", integrity) |
| 35 | } |
| 36 | _, _ = handle.DB.ExecContext(ctx, `PRAGMA wal_checkpoint(TRUNCATE)`) |
| 37 | if err := handle.DB.Close(); err != nil { |
| 38 | cleanupTemporary() |
| 39 | return err |
| 40 | } |
| 41 | if err := ctx.Err(); err != nil { |
| 42 | if opts.ResumeKey == "" { |
| 43 | cleanupTemporary() |
| 44 | } |
| 45 | return err |
| 46 | } |
| 47 | |
| 48 | return nil |
| 49 | } |
| 50 |