|
1 | 1 | package system |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "fmt" |
| 5 | + "github.com/siddontang/go-mysql/mysql" |
4 | 6 | "horgh-replicator/src/constants" |
| 7 | + "horgh-replicator/src/tools/exit" |
| 8 | + "io/ioutil" |
| 9 | + "os" |
| 10 | + "strconv" |
| 11 | + "strings" |
5 | 12 | ) |
6 | 13 |
|
7 | | -type replicator struct { |
8 | | - Key string `gorm:"column:param_key"` |
9 | | - Value string `gorm:"column:param_value"` |
10 | | -} |
11 | | - |
12 | | -func GetValue(key string) string { |
13 | | - query := `SELECT * FROM param_values WHERE param_key=? LIMIT 1;` |
14 | | - params := []interface{}{ |
15 | | - key, |
16 | | - } |
17 | | - |
18 | | - res := Get(constants.DBReplicator, map[string]interface{}{ |
19 | | - "query": query, |
20 | | - "params": params, |
21 | | - }) |
22 | | - |
23 | | - var row replicator |
24 | | - for res.Next() { |
25 | | - err := res.Scan(&row.Key, &row.Value) |
26 | | - if err != nil { |
27 | | - panic(err.Error()) |
28 | | - } |
29 | | - } |
30 | | - result := row.Value |
| 14 | +const ( |
| 15 | + PositionMask = "%s:%s" |
| 16 | +) |
31 | 17 |
|
32 | | - defer func() { |
33 | | - _ = res.Close() |
34 | | - }() |
| 18 | +func SetPosition(hash string, position mysql.Position) error { |
| 19 | + content := fmt.Sprintf(PositionMask, position.Name, strconv.Itoa(int(position.Pos))) |
| 20 | + fileName := fmt.Sprintf(constants.PositionsPath, hash) |
| 21 | + err := ioutil.WriteFile(fileName, []byte(content), 0644) |
35 | 22 |
|
36 | | - return result |
| 23 | + return err |
37 | 24 | } |
38 | 25 |
|
39 | | -func SetValue(key string, value string) bool { |
40 | | - query := `INSERT INTO param_values(param_key, param_value) VALUES(?, ?) ON DUPLICATE KEY UPDATE param_value=?;` |
41 | | - params := []interface{}{ |
42 | | - key, |
43 | | - value, |
44 | | - value, |
| 26 | +func GetPosition(hash string) mysql.Position { |
| 27 | + fileName := fmt.Sprintf(constants.PositionsPath, hash) |
| 28 | + |
| 29 | + if _, err := os.Stat(fileName); os.IsNotExist(err) { |
| 30 | + return mysql.Position{} |
45 | 31 | } |
46 | 32 |
|
47 | | - res := Exec(constants.DBReplicator, map[string]interface{}{ |
48 | | - "query": query, |
49 | | - "params": params, |
50 | | - }) |
| 33 | + content, err := ioutil.ReadFile(fileName) |
| 34 | + if err != nil { |
| 35 | + exit.Fatal(constants.ErrorGetPosition, err.Error()) |
| 36 | + } |
| 37 | + data := strings.Split(string(content[:]), ":") |
| 38 | + if len(data) != 2 { |
| 39 | + exit.Fatal(constants.ErrorGetPosition, "Can't parse position") |
| 40 | + } |
| 41 | + position, err := strconv.Atoi(data[1]) |
| 42 | + if err != nil { |
| 43 | + exit.Fatal(constants.ErrorGetPosition, err.Error()) |
| 44 | + } |
| 45 | + pos := mysql.Position{ |
| 46 | + Name: data[0], |
| 47 | + Pos: uint32(position), |
| 48 | + } |
51 | 49 |
|
52 | | - return res |
| 50 | + return pos |
53 | 51 | } |
0 commit comments