-
Notifications
You must be signed in to change notification settings - Fork 0
/
repository_service.go
105 lines (85 loc) · 1.9 KB
/
repository_service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"context"
"fmt"
"os"
"github.com/jmoiron/sqlx"
sqlite3 "modernc.org/sqlite"
)
type RepositoryService struct {
shouldDestroy bool
file string
db *sqlx.DB
}
func NewRepositoryService(file string, db *sqlx.DB) *RepositoryService {
repositoryService := RepositoryService{
file: file,
db: db,
shouldDestroy: false,
}
return &repositoryService
}
func (rs *RepositoryService) Destroy() {
rs.shouldDestroy = true
}
func (rs *RepositoryService) Close() error {
if rs.shouldDestroy {
defer rs.destroy()
}
return rs.db.Close()
}
type backuper interface {
NewBackup(string) (*sqlite3.Backup, error)
NewRestore(string) (*sqlite3.Backup, error)
}
func (rs *RepositoryService) Backup(file string) error {
conn, err := rs.db.Conn(context.Background())
if err != nil {
return fmt.Errorf("db conn: %w", err)
}
defer conn.Close()
err = conn.Raw(func(driverConn any) error {
bck, err := driverConn.(backuper).NewBackup(file)
if err != nil {
return fmt.Errorf("NewBackup: %w", err)
}
for more := true; more; {
more, err = bck.Step(-1)
if err != nil {
return fmt.Errorf("bkp step: %w", err)
}
}
return bck.Finish()
})
if err != nil {
return fmt.Errorf("bkp: %w", err)
}
return nil
}
func (rs *RepositoryService) Restore(file string) error {
conn, err := rs.db.Conn(context.Background())
if err != nil {
return fmt.Errorf("db conn: %w", err)
}
defer conn.Close()
err = conn.Raw(func(driverConn any) error {
bck, err := driverConn.(backuper).NewRestore(file)
if err != nil {
return fmt.Errorf("NewRestore: %w", err)
}
for more := true; more; {
more, err = bck.Step(-1)
if err != nil {
return fmt.Errorf("restore step: %w", err)
}
}
return bck.Finish()
})
if err != nil {
return fmt.Errorf("bkp: %w", err)
}
return nil
}
func (rs *RepositoryService) destroy() {
os.Remove(rs.file)
}