Repository navigation
Expand file tree
/
Copy pathdiff.go
More file actions
114 lines (105 loc) · 2.31 KB
/
Copy pathdiff.go
File metadata and controls
114 lines (105 loc) · 2.31 KB
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
106
107
108
109
110
111
112
113
114
package main
import (
"database/sql"
"fmt"
"log"
"strconv"
)
// CompareType contents compare type
type CompareType int
// CompareType enum..
const (
UPDATE CompareType = iota + 1
INSERT
DELETE
)
// KeyValue : key value store
type KeyValue struct {
Key string
Value interface{}
}
func (kv *KeyValue) String() string {
switch kv.Value.(type) {
case int:
return fmt.Sprintf("%20d", kv.Value.(int))
case float64:
return fmt.Sprintf("%20f", kv.Value.(float64))
default:
return kv.Value.(string)
}
// log.Fatalln("not found key type!", kv)
}
// DiffRow : diff row info.
type DiffRow struct {
Compare CompareType // 1=alter , 2 = insert, 3 = delete
Data []*KeyValue
Keys []*KeyValue
table string
}
// GetKey : get key data string
func (d *DiffRow) GetKey() string {
var result string
for _, k := range d.Keys {
result += fmt.Sprintf("%s|", k)
}
return result
}
func getDataStr(v interface{}) string {
switch t := v.(type) {
case string:
return fmt.Sprintf("'%s'", v.(string))
case int:
return strconv.Itoa(v.(int))
case float64:
return strconv.FormatFloat(v.(float64), 'f', -1, 64)
case sql.RawBytes:
var hex = fmt.Sprintf("%X", v)
return fmt.Sprintf("X'%s'", hex)
case nil:
return "NULL"
default:
log.Fatalln("check type..", t)
}
return ""
}
// GenerateSQL : generate sql string
func (d *DiffRow) GenerateSQL(table string) string {
switch d.Compare {
case INSERT:
var keys, values string
for _, d := range d.Data {
if len(keys) > 0 {
keys += ", "
values += ", "
}
keys += fmt.Sprintf("`%s`", d.Key)
values += getDataStr(d.Value)
}
return fmt.Sprintf("INSERT INTO `%s` (%s) VALUES (%s);", table, keys, values)
case UPDATE:
var keys, values string
for _, k := range d.Keys {
if len(keys) > 0 {
keys += " AND "
}
keys += fmt.Sprintf("`%s` = %s", k.Key, getDataStr(k.Value))
}
for _, d := range d.Data {
if len(values) > 0 {
values += ", "
}
values += fmt.Sprintf("`%s` = %s", d.Key, getDataStr(d.Value))
}
return fmt.Sprintf("UPDATE `%s` SET %s WHERE %s;", table, values, keys)
case DELETE:
var keys string
for _, k := range d.Keys {
if len(keys) > 0 {
keys += " AND "
}
keys += fmt.Sprintf("`%s` = %s", k.Key, getDataStr(k.Value))
}
return fmt.Sprintf("DELETE FROM `%s` WHERE %s;", table, keys)
}
return ""
}