forked from jamf/go-mysqldump
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysqldump.go
86 lines (74 loc) · 1.65 KB
/
mysqldump.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
package mysqldump
import (
"database/sql"
"errors"
"io"
"os"
"path"
"time"
)
/*
Register a new dumper.
db: Database that will be dumped (https://golang.org/pkg/database/sql/#DB).
dir: Path to the directory where the dumps will be stored.
format: Format to be used to name each dump file. Uses time.Time.Format (https://golang.org/pkg/time/#Time.Format). format appended with '.sql'.
*/
func Register(db *sql.DB, dir, format string) (*Data, error) {
if !isDir(dir) {
return nil, errors.New("Invalid directory")
}
name := time.Now().Format(format)
p := path.Join(dir, name+".sql")
// Check dump directory
if e, _ := exists(p); e {
return nil, errors.New("Dump '" + name + "' already exists.")
}
// Create .sql file
f, err := os.Create(p)
if err != nil {
return nil, err
}
return &Data{
Out: f,
Connection: db,
}, nil
}
// Dump Creates a MYSQL dump from the connection to the stream.
func Dump(db *sql.DB, out io.Writer) error {
return (&Data{
Connection: db,
Out: out,
}).Dump()
}
// Close the dumper.
// Will also close the database the dumper is connected to as well as the out stream if it has a Close method.
//
// Not required.
func (data *Data) Close() error {
defer func() {
data.Connection = nil
data.Out = nil
}()
if out, ok := data.Out.(io.Closer); ok {
out.Close()
}
return data.Connection.Close()
}
func exists(p string) (bool, os.FileInfo) {
f, err := os.Open(p)
if err != nil {
return false, nil
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return false, nil
}
return true, fi
}
func isDir(p string) bool {
if e, fi := exists(p); e {
return fi.Mode().IsDir()
}
return false
}