zhangqian
2024-04-25 2d6875c93b25d0b7336c7fa11e066d213259fe2e
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
package serf
 
import (
    "errors"
    "fmt"
    "strings"
 
    "github.com/jinzhu/gorm"
)
 
type DumpSql struct {
    Sql string `json:"sql"`
}
 
type TableDesc struct {
    Cid       int         `json:"cid"`
    Name      string      `json:"name"`
    Type      string      `json:"type"`
    Notnull   bool        `json:"notnull"`
    DFltValue interface{} `json:"dflt_value"`
    Pk        int         `json:"pk"`
}
 
var syncSqlChan = make(chan string, 10)
 
func DumpTables(db *gorm.DB, tableNames []string) ([]string, error) {
    db.LogMode(false)
    defer db.LogMode(true)
 
    if tableNames != nil {
        var arr []string
        var dumpSql []DumpSql
 
        for _, table := range tableNames {
            fmt.Println("dump current tableName:", table)
 
            dumpSql = make([]DumpSql, 0)
            var tDescArr []TableDesc
 
            tSql := fmt.Sprintf(`PRAGMA table_info("%s")`, table)
            err := db.Raw(tSql).Scan(&tDescArr).Error
            if err != nil {
                return nil, errors.New("tableDesc err")
            }
 
            if tDescArr == nil || len(tDescArr) == 0 {
                continue
            }
 
            var columnNames []string
            var columnValues []string
            for _, col := range tDescArr {
                columnNames = append(columnNames, col.Name)
                columnValues = append(columnValues, fmt.Sprintf(`'||quote("%s")||'`, col.Name))
            }
 
            tSql = fmt.Sprintf(`SELECT 'INSERT INTO "%s" (%s) VALUES(%s)' as sql FROM "%s";`,
                table,
                strings.Join(columnNames, ","),
                strings.Join(columnValues, ","),
                table)
            //fmt.Println("tSql:", tSql)
 
            err = db.Raw(tSql).Scan(&dumpSql).Error
            if err != nil {
                return nil, errors.New("dump err")
            }
 
            if len(dumpSql) > 0 {
                for _, d := range dumpSql {
                    arr = append(arr, d.Sql)
                }
            }
        }
 
        return arr, nil
    }
 
    return nil, errors.New("tableNames is nil")
}