-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
104 lines (95 loc) · 1.79 KB
/
server.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
package pgctl
import (
"os"
"sync"
)
// Server represents PostgreSQL instance.
type Server struct {
m sync.Mutex
r bool
dir string
io InitDBOptions
so StartOptions
}
// NewServer creates an instance of PostgreSQL.
func NewServer(dataDir string) *Server {
return &Server{dir: dataDir}
}
// InitDBOptions sets InitDBOptions
func (srv *Server) InitDBOptions(io *InitDBOptions) error {
srv.m.Lock()
defer srv.m.Unlock()
if srv.r {
return ErrAlreadyRunning
}
if io != nil {
srv.io = *io
} else {
srv.io = InitDBOptions{}
}
return nil
}
// StartOptions sets StartOptions
func (srv *Server) StartOptions(so *StartOptions) error {
srv.m.Lock()
defer srv.m.Unlock()
if srv.r {
return ErrAlreadyRunning
}
if so != nil {
srv.so = *so
} else {
srv.so = StartOptions{}
}
return nil
}
// Start starts PostgreSQL in background.
func (srv *Server) Start() error {
srv.m.Lock()
defer srv.m.Unlock()
if srv.r {
return ErrAlreadyRunning
}
if _, err := os.Stat(srv.dir); err != nil {
if !os.IsNotExist(err) {
return err
}
if err := InitDB(srv.dir, &srv.io); err != nil {
return err
}
}
if err := Start(srv.dir, &srv.so); err != nil {
return err
}
srv.r = true
return nil
}
// Stop stops an instance of PostgreSQL.
func (srv *Server) Stop() error {
srv.m.Lock()
defer srv.m.Unlock()
if !srv.r {
return ErrNotRunning
}
if err := Stop(srv.dir); err != nil {
return err
}
srv.r = false
return nil
}
// IsRunning checks PostgreSQL server is running or not.
func (srv *Server) IsRunning() bool {
srv.m.Lock()
defer srv.m.Unlock()
return srv.r
}
// Name returns data source name if server is running.
// Otherwise returns empty string.
func (srv *Server) Name() string {
srv.m.Lock()
defer srv.m.Unlock()
if !srv.r {
return ""
}
return Name(&srv.io, &srv.so)
}