-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysql_import_db_struct.go
75 lines (70 loc) · 1.92 KB
/
mysql_import_db_struct.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
package mysql
import (
"context"
"path/filepath"
"github.com/admpub/nging/v5/application/library/common"
"github.com/admpub/nging/v5/application/library/notice"
"github.com/webx-top/com"
"github.com/webx-top/db/lib/factory"
)
func (m *mySQL) exec(sqlStr string, dbfactory ...*factory.Factory) (int64, error) {
result, err := m.newParam(dbfactory...).SetCollection(sqlStr).Exec()
if err != nil {
return 0, err
}
return result.RowsAffected()
}
// importDBStruct 导出表结构
func (m *mySQL) importDBStruct(ctx context.Context, noticer *notice.NoticeAndProgress,
dbfactory *factory.Factory, sqlFiles []string) (err error) {
exec := func(sqlFile string, callback func(strLen int)) func(string) error {
return common.SQLLineParser(func(sqlStr string) error {
_, err := m.exec(sqlStr, dbfactory)
if err != nil {
noticer.Failure(`[FAILURE] ` + err.Error() + `: ` + com.HTMLEncode(sqlStr) + `: ` + filepath.Base(sqlFile))
} else {
noticer.Success(`[SUCCESS] ` + filepath.Base(sqlFile))
}
callback(len(sqlStr))
return err
})
}
for _, sqlFile := range sqlFiles {
err = execSQLFileWithProgress(noticer, sqlFile, exec)
if err != nil {
return
}
}
return err
}
func execSQLFileWithProgress(
noticer *notice.NoticeAndProgress,
sqlFile string,
exec func(sqlFile string, callback func(strLen int)) func(string) error,
) error {
fileSize, _ := com.FileSize(sqlFile)
var remains int64 = 100
var partPercent float64
var perByteVal float64
if fileSize > 0 {
perByteVal = float64(remains) / float64(fileSize)
}
var callback = func(strLen int) {
if perByteVal <= 0 {
return
}
partPercent += perByteVal * float64(strLen)
if partPercent < 1 {
return
}
percent := int64(partPercent)
remains -= percent
noticer.Done(percent)
partPercent = partPercent - float64(percent)
}
err := com.SeekFileLines(sqlFile, exec(sqlFile, callback))
if remains > 0 {
noticer.Done(remains)
}
return err
}