( ctx context.Context, path string, pragmas []string, initialize func(context.Context, *sql.DB) error, )
| 44 | } |
| 45 | |
| 46 | func openSQLiteDatabaseWithPragmas( |
| 47 | ctx context.Context, |
| 48 | path string, |
| 49 | pragmas []string, |
| 50 | initialize func(context.Context, *sql.DB) error, |
| 51 | ) (*sql.DB, error) { |
| 52 | cleanPath := strings.TrimSpace(path) |
| 53 | if cleanPath == "" { |
| 54 | return nil, errors.New("store: database path is required") |
| 55 | } |
| 56 | if err := os.MkdirAll(filepath.Dir(cleanPath), 0o755); err != nil { |
| 57 | return nil, fmt.Errorf("store: create database directory for %q: %w", cleanPath, err) |
| 58 | } |
| 59 | |
| 60 | db, err := openSQLiteDatabaseOnce(ctx, cleanPath, initialize, pragmas...) |
| 61 | if err == nil { |
| 62 | return db, nil |
| 63 | } |
| 64 | if !ShouldRecoverSQLite(err) { |
| 65 | return nil, err |
| 66 | } |
| 67 | if _, statErr := os.Stat(cleanPath); statErr != nil { |
| 68 | return nil, err |
| 69 | } |
| 70 | if _, recoverErr := recoverSQLiteDatabase(cleanPath); recoverErr != nil { |
| 71 | return nil, errors.Join(err, fmt.Errorf("store: recover sqlite database %q: %w", cleanPath, recoverErr)) |
| 72 | } |
| 73 | |
| 74 | db, reopenErr := openSQLiteDatabaseOnce(ctx, cleanPath, initialize, pragmas...) |
| 75 | if reopenErr != nil { |
| 76 | return nil, errors.Join( |
| 77 | err, |
| 78 | fmt.Errorf("store: reopen sqlite database %q after recovery: %w", cleanPath, reopenErr), |
| 79 | ) |
| 80 | } |
| 81 | return db, nil |
| 82 | } |
| 83 | |
| 84 | func openSQLiteDatabaseOnce( |
| 85 | ctx context.Context, |
no test coverage detected