-
Notifications
You must be signed in to change notification settings - Fork 2
/
dao.go
261 lines (213 loc) · 5.21 KB
/
dao.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
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
// Copyright 2022 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"database/sql"
"fmt"
"math/rand"
"strings"
"github.com/google/uuid"
)
type Player struct {
ID string
Coins int
Goods int
}
// recreateTable recreate table
func recreateTable(db *sql.DB) {
if _, err := db.Exec(DropTableSQL); err != nil {
panic(err)
}
if _, err := db.Exec(CreateTableSQL); err != nil {
panic(err)
}
}
// createPlayer create a player
func createPlayer(db *sql.DB, player Player) error {
_, err := db.Exec(CreatePlayerSQL, player.ID, player.Coins, player.Goods)
return err
}
// getPlayer get a player
func getPlayer(db *sql.DB, id string) (Player, error) {
var player Player
rows, err := db.Query(GetPlayerSQL, id)
if err != nil {
return player, err
}
defer rows.Close()
if rows.Next() {
err = rows.Scan(&player.ID, &player.Coins, &player.Goods)
if err == nil {
return player, nil
} else {
return player, err
}
}
return player, fmt.Errorf("can not found player")
}
// getPlayerByLimit get players by limit
func getPlayerByLimit(db *sql.DB, limit int) ([]Player, error) {
var players []Player
rows, err := db.Query(GetPlayerByLimitSQL, limit)
if err != nil {
return players, err
}
defer rows.Close()
for rows.Next() {
player := Player{}
err = rows.Scan(&player.ID, &player.Coins, &player.Goods)
if err == nil {
players = append(players, player)
} else {
return players, err
}
}
return players, nil
}
// bulk-insert players
func bulkInsertPlayers(db *sql.DB, players []Player, batchSize int) error {
tx, err := TiDBSqlBegin(db, true)
if err != nil {
return err
}
stmt, err := tx.Prepare(buildBulkInsertSQL(batchSize))
if err != nil {
return err
}
defer stmt.Close()
for len(players) > batchSize {
if _, err := stmt.Exec(playerToArgs(players[:batchSize])...); err != nil {
tx.Rollback()
return err
}
players = players[batchSize:]
}
if len(players) != 0 {
if _, err := tx.Exec(buildBulkInsertSQL(len(players)), playerToArgs(players)...); err != nil {
tx.Rollback()
return err
}
}
if err := tx.Commit(); err != nil {
tx.Rollback()
return err
}
return nil
}
func getCount(db *sql.DB) (int, error) {
count := 0
rows, err := db.Query(GetCountSQL)
if err != nil {
return count, err
}
defer rows.Close()
if rows.Next() {
if err := rows.Scan(&count); err != nil {
return count, err
}
}
return count, nil
}
func tradeCheck(tx *TiDBSqlTx, sellID, buyID string, amount, price int) error {
var sellPlayer, buyPlayer Player
stmt, err := tx.Prepare(GetPlayerWithLockSQL)
if err != nil {
return err
}
defer stmt.Close()
sellRows, err := stmt.Query(sellID)
if err != nil {
return err
}
defer sellRows.Close()
if sellRows.Next() {
if err := sellRows.Scan(&sellPlayer.ID, &sellPlayer.Coins, &sellPlayer.Goods); err != nil {
return err
}
}
sellRows.Close()
if sellPlayer.ID != sellID || sellPlayer.Goods < amount {
return fmt.Errorf("sell player %s goods not enough", sellID)
}
buyRows, err := stmt.Query(buyID)
if err != nil {
return err
}
defer buyRows.Close()
if buyRows.Next() {
if err := buyRows.Scan(&buyPlayer.ID, &buyPlayer.Coins, &buyPlayer.Goods); err != nil {
return err
}
}
buyRows.Close()
if buyPlayer.ID != buyID || buyPlayer.Coins < price {
return fmt.Errorf("buy player %s coins not enough", buyID)
}
return nil
}
func tradeUpdate(tx *TiDBSqlTx, sellID, buyID string, amount, price int) error {
updateStmt, err := tx.Prepare(UpdatePlayerSQL)
if err != nil {
return err
}
defer updateStmt.Close()
if _, err := updateStmt.Exec(-amount, price, sellID); err != nil {
return err
}
if _, err := updateStmt.Exec(amount, -price, buyID); err != nil {
return err
}
return nil
}
func buyGoods(db *sql.DB, sellID, buyID string, amount, price int) error {
tx, err := TiDBSqlBegin(db, true)
if err != nil {
return err
}
buyExec := func() error {
if err := tradeCheck(tx, sellID, buyID, amount, price); err != nil {
return err
}
return tradeUpdate(tx, sellID, buyID, amount, price)
}
err = buyExec()
if err == nil {
fmt.Println("\n[buyGoods]:\n 'trade success'")
tx.Commit()
} else {
tx.Rollback()
}
return err
}
func playerToArgs(players []Player) []interface{} {
var args []interface{}
for _, player := range players {
args = append(args, player.ID, player.Coins, player.Goods)
}
return args
}
func buildBulkInsertSQL(amount int) string {
return CreatePlayerSQL + strings.Repeat(",(?,?,?)", amount-1)
}
func randomPlayers(amount int) []Player {
players := make([]Player, amount, amount)
for i := 0; i < amount; i++ {
players[i] = Player{
ID: uuid.New().String(),
Coins: rand.Intn(10000),
Goods: rand.Intn(10000),
}
}
return players
}