Blame view

src/services/dbseed.lua 9.81 KB
314bc5df   zhengshouren   提交服务器初始代码
1
2
3
4
5
6
  require "shared.init"
  require "utils.init"
  require "GlobalVar"
  require "RedisKeys"
  require "ProtocolCode"
  require "skynet.manager"
913e070e   liuzujun   添加订单表,全局id定时回写数据库
7
  require "utils.MysqlUtil"
314bc5df   zhengshouren   提交服务器初始代码
8
9
10
11
  
  skynet = require "skynet"
  
  redisproxy = require("shared.redisproxy")
0de80321   liuzujun   创建游戏数据库,role对应mys...
12
  mysqlproxy = require "shared.mysqlproxy"
314bc5df   zhengshouren   提交服务器初始代码
13
14
15
  
  SendPacket = function ( ... ) end
  
1279810c   liuzujun   海港贸易任务新增表
16
17
18
19
20
21
22
23
24
25
  local function initSeaportTask()
  	local keys = {[SEAPORT_TRADE_TASK_1] = "seaport_task_1", [SEAPORT_TRADE_TASK_2] = "seaport_task_2"}
  
  	for key, tb_name in pairs(keys) do
  		local res = mysqlproxy:query(string.format("SELECT `id`,`value` FROM %s;", tb_name))
  		for _, v in pairs(res) do
  			redisproxy:hset(key, v.id, v.value)
  		end
  	end
  end
913e070e   liuzujun   添加订单表,全局id定时回写数据库
26
  
314bc5df   zhengshouren   提交服务器初始代码
27
  local function initRedisDb( ... )
913e070e   liuzujun   添加订单表,全局id定时回写数据库
28
29
30
31
32
33
34
35
  	local function initAutoIncrementUid(tbName, keyName, fieldName)
  		if not fieldName then fieldName = "value" end
  		local mysqlVal = getDbCfgVal(tbName, keyName, fieldName)
  		if not mysqlVal then 
  			skynet.error(string.format("get db cfg fail, table %s, key %s, field %s", tbName, keyName, fieldName))
  			return
  		end
  		local redisVal = tonum(redisproxy:hget(tbName, keyName))
344d2df3   liuzujun   微信支付宝下单接口
36
  		if redisVal < mysqlVal or redisVal == 0 then
913e070e   liuzujun   添加订单表,全局id定时回写数据库
37
38
  			redisproxy:hset(tbName, keyName, mysqlVal)
  		end
314bc5df   zhengshouren   提交服务器初始代码
39
  	end
913e070e   liuzujun   添加订单表,全局id定时回写数据库
40
41
42
43
44
45
46
  
  	initAutoIncrementUid("autoincrement_set", "role")
  	initAutoIncrementUid("autoincrement_set", "union")
  	initAutoIncrementUid("autoincrement_set", "order")
  	initAutoIncrementUid("autoincrement_set", "email")
  	initAutoIncrementUid("autoincrement_set", "emailTimestamp")
  	initAutoIncrementUid("autoincrement_set", "delay_email")
6136eaca   liuzujun   添加好友表
47
48
  	initAutoIncrementUid("autoincrement_set", "stopcreate")
  	initAutoIncrementUid("autoincrement_set", "maintain")
1279810c   liuzujun   海港贸易任务新增表
49
50
51
  	initAutoIncrementUid("autoincrement_set", "seaportTime0")
  	initAutoIncrementUid("autoincrement_set", "seaportTime1")
  	initAutoIncrementUid("autoincrement_set", "seaportTime2")
913e070e   liuzujun   添加订单表,全局id定时回写数据库
52
  
1279810c   liuzujun   海港贸易任务新增表
53
54
55
  	redisproxy:hsetnx("adv_season", "idx", 0)
  	redisproxy:hsetnx("adv_season", "chapter", globalCsv.adv_endless_default_chapter)
  	redisproxy:hsetnx("adv_season", "overTime", 0)
314bc5df   zhengshouren   提交服务器初始代码
56
57
  end
  
0de80321   liuzujun   创建游戏数据库,role对应mys...
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
  -- 初始化服务器数据库以及服务器信息表
  local function initServerDatabase()
  	local servId = skynet.getenv("servId")
  	mysqlproxy:query(string.format("CREATE DATABASE IF NOT EXISTS server_%s DEFAULT CHARSET = utf8mb4 COLLATE utf8mb4_general_ci;", servId))
  	mysqlproxy:query(string.format("use server_%s", servId))
  
  	-- 服务器信息表 开服时间
  	mysqlproxy:query [[
  		CREATE TABLE IF NOT EXISTS `server_info` (
  			`key` varchar(45) NOT NULL,
  			`int_value` int(11) DEFAULT NULL,
  			`str_value` varchar(128) DEFAULT NULL,
  			PRIMARY KEY (`key`)
  			) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
  	]]
  
  	local res = mysqlproxy:query("SELECT * FROM `server_info` where `key` = 'server_start';")
  	if not next(res) then
  		mysqlproxy:query(string.format("INSERT INTO `server_info`(`key`, `str_value`) VALUES('server_start', '%s');",
  			os.date("%Y%m%d", skynet.timex())))
  	end
  end
  
  local function initAutoIncreUidTable()
  	mysqlproxy:query [[
913e070e   liuzujun   添加订单表,全局id定时回写数据库
83
  		CREATE TABLE IF NOT EXISTS `autoincrement_set` (
0de80321   liuzujun   创建游戏数据库,role对应mys...
84
85
86
87
88
89
90
  			`key` varchar(45) NOT NULL,
  			`value` int(11) DEFAULT NULL,
  			PRIMARY KEY (`key`)
  			) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
  	]]
  	local servId = tonumber(skynet.getenv("servId"))
  	if servId then
913e070e   liuzujun   添加订单表,全局id定时回写数据库
91
  		local tpl = "INSERT INTO `autoincrement_set`(`key`, `value`) values('%s', %d)"
0de80321   liuzujun   创建游戏数据库,role对应mys...
92
93
  		mysqlproxy:query(string.format(tpl, "role", servId * MAX_ROLE_NUM))
  		mysqlproxy:query(string.format(tpl, "union", servId * MAX_ROLE_NUM))
913e070e   liuzujun   添加订单表,全局id定时回写数据库
94
  		mysqlproxy:query(string.format(tpl, "order", 0))
0de80321   liuzujun   创建游戏数据库,role对应mys...
95
96
97
  		mysqlproxy:query(string.format(tpl, "email", 0))
  		mysqlproxy:query(string.format(tpl, "emailTimestamp", 0))
  		mysqlproxy:query(string.format(tpl, "delay_email", 0))
6136eaca   liuzujun   添加好友表
98
99
  		mysqlproxy:query(string.format(tpl, "stopcreate", 0))
  		mysqlproxy:query(string.format(tpl, "maintain", 0))
1279810c   liuzujun   海港贸易任务新增表
100
101
102
  		mysqlproxy:query(string.format(tpl, "seaportTime0", 0))
  		mysqlproxy:query(string.format(tpl, "seaportTime1", 0))
  		mysqlproxy:query(string.format(tpl, "seaportTime2", 0))
e9bfa7a2   liuzujun   其他玩家展示界面数据支持, 更新s...
103
104
105
  
          -- 记录当前更新版本
  		mysqlproxy:query(string.format(tpl, "db_ver", 0))
0de80321   liuzujun   创建游戏数据库,role对应mys...
106
107
108
  	end
  end
  
1279810c   liuzujun   海港贸易任务新增表
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
  local function initSeaportTable()
  	-- 海港贸易任务
  	mysqlproxy:query [[
  		CREATE TABLE IF NOT EXISTS `seaport_task_1` (
  			`id` int NOT NULL,
  			`value` int(11) DEFAULT 0,
  			PRIMARY KEY (`id`)
  			) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
  	]]
  	mysqlproxy:query [[
  		CREATE TABLE IF NOT EXISTS `seaport_task_2` (
  			`id` int NOT NULL,
  			`value` int(11) DEFAULT 0,
  			PRIMARY KEY (`id`)
  			) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
  	]]
  end
  
0de80321   liuzujun   创建游戏数据库,role对应mys...
127
  local function initAdvSeasonTable()
ec0df561   liuzujun   创建及时保存一次
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
  	--mysqlproxy:query [[
  	--	CREATE TABLE IF NOT EXISTS `adv_season` (
  	--		`key` varchar(45) NOT NULL,
  	--		`value` int(11) DEFAULT NULL,
  	--		PRIMARY KEY (`key`)
  	--		) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
  	--]]
  	--local servId = tonumber(skynet.getenv("servId"))
  	--if servId then
  	--	local tpl = "INSERT INTO `adv_season`(`key`, `value`) values('%s', %d)"
  
  	--	mysqlproxy:query(string.format(tpl, "idx", 0))
  	--	mysqlproxy:query(string.format(tpl, "chapter", globalCsv.adv_endless_default_chapter))
  	--	mysqlproxy:query(string.format(tpl, "overTime", 0))
  	--end
0de80321   liuzujun   创建游戏数据库,role对应mys...
143
144
145
  end
  
  local function checkRoleTables()
d99a4962   liuzujun   火花系统建表,新增虹光玉
146
  	local list = {"Role", "Daily", "Activity", "Diner", "Store", "Hero", "Rune", "Order", "Email", "Friend", "Spark"}
fa992c94   liuzujun   添加daily,diner,act...
147
148
149
150
151
152
  	for _, name in ipairs(list) do
  		local obj = require("models."..name).new({key = "key"})
  		print("check table [" .. name .. "] begin.")
  		obj:checkTableSchema()
  		print("check table [" .. name .. "] end.")
  	end
0de80321   liuzujun   创建游戏数据库,role对应mys...
153
154
  end
  
6136eaca   liuzujun   添加好友表
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
  local function createMysqlSp()
  	mysqlproxy:query "DROP PROCEDURE IF EXISTS `add_friends`"
  	mysqlproxy:query [[
  		CREATE PROCEDURE `add_friends`(IN role_id bigint, IN friend_id bigint, IN add_time int)
  		BEGIN
  			DECLARE t_error INTEGER DEFAULT 0;    
  			DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET t_error=1;    
      
  			START TRANSACTION;    
  				INSERT INTO `Friend`(`roleid`,`fid`,`addTime`) VALUES(role_id, friend_id, add_time);       
  				INSERT INTO `Friend`(`roleid`,`fid`,`addTime`) VALUES(friend_id, role_id, add_time);       
      
  			IF t_error = 1 THEN    
  				ROLLBACK;    
  			ELSE    
  				COMMIT;    
  			END IF;    
  			select t_error; 
  		END
  	]]
  
  	mysqlproxy:query "DROP PROCEDURE IF EXISTS `del_friends`"
  	mysqlproxy:query [[
  		CREATE PROCEDURE `del_friends`(IN role_id bigint, IN friend_id bigint)
  		BEGIN
  			DECLARE t_error INTEGER DEFAULT 0;    
  			DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET t_error=1;    
      
  			START TRANSACTION;    
  				DELETE FROM `Friend` WHERE `roleid` = role_id AND `fid` = friend_id;       
  				DELETE FROM `Friend` WHERE `roleid` = friend_id AND `fid` = role_id;       
      
  			IF t_error = 1 THEN    
  				ROLLBACK;    
  			ELSE    
  				COMMIT;    
  			END IF;    
  			select t_error; 
  		END
  	]]
  end
  
1279810c   liuzujun   海港贸易任务新增表
197
  
314bc5df   zhengshouren   提交服务器初始代码
198
199
  local steps = {
  	[1] = {
0de80321   liuzujun   创建游戏数据库,role对应mys...
200
201
202
  		handler = initServerDatabase,
  		desc = "initialize server database "
  	},
913e070e   liuzujun   添加订单表,全局id定时回写数据库
203
  	[2] = {
0de80321   liuzujun   创建游戏数据库,role对应mys...
204
205
206
  		handler = initAutoIncreUidTable,
  		desc = "initialize auto_increment_uid table "
  	},
ec0df561   liuzujun   创建及时保存一次
207
208
209
210
  	[3] = {
  		handler = initAdvSeasonTable,
  		desc = "initialize adv_season table "
  	},
913e070e   liuzujun   添加订单表,全局id定时回写数据库
211
  	[4] = {
0de80321   liuzujun   创建游戏数据库,role对应mys...
212
213
  		handler = checkRoleTables,
  		desc = "check role tables "
6136eaca   liuzujun   添加好友表
214
215
216
217
218
  	},
  	[5] = {
  		handler = createMysqlSp,
  		desc = "create mysql store procedure "
  	},
1279810c   liuzujun   海港贸易任务新增表
219
220
221
222
  	[6] = {
  		handler = initSeaportTable,
  		desc = "initialize seaport table "
  	},
314bc5df   zhengshouren   提交服务器初始代码
223
224
  }
  
6136eaca   liuzujun   添加好友表
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
  local function loadAllUserInfo()
  	local maxId = 0
  	local sql = "SELECT `id`, `uid`, `name` FROM `Role` WHERE `id` > %d ORDER BY `id` LIMIT 1000;"
  	while true do
  		local res = mysqlproxy:query(string.format(sql, maxId))
  		if not next(res) then
  			return
  		else
  			for _, info in ipairs(res) do
  				if info["id"] > maxId then
  					maxId = info["id"]
  				end
  				redisproxy:pipelining(function (red)
  					local dbName = string.upper(info["name"])
  					red:set(string.format("user:%s", dbName), info["id"])
  					red:set(string.format("uid:%s", info["uid"]), dbName)
  				end)
  			end
  		end
  	end
  end
  
2f414c31   liuzujun   初始化选择对应游戏数据库
247
248
249
250
251
252
253
254
255
256
257
258
259
260
  local function selectDb()
  	local work_count = tonumber(skynet.getenv("thread"))
  	for i = 1, work_count do
  		local mysqld = skynet.localname(".mysql" .. i)
  
  		local servId = skynet.getenv("servId")
  		local ok, result = pcall(skynet.call, mysqld, "lua", "query", string.format("use server_%s", servId))
  		if not ok then
  			skynet.error("select db error", "\n", debug.traceback(coroutine.running(), nil))
  			return
  		end
  	end
  end
  
e9bfa7a2   liuzujun   其他玩家展示界面数据支持, 更新s...
261
262
263
264
265
266
  local function doUpdateSql()
      local updates = {
          [1] = {
              "ALTER TABLE `Email` ADD INDEX roleid_createtime_id(`roleId`,`createtime`,`id`),DROP INDEX roleId_Index",
              "ALTER TABLE `Role` ADD INDEX uid_Index(`uid`)",
          },
8284146d   liuzujun   修改rune表refer字段位bi...
267
268
          [2] = {
              "ALTER TABLE `Rune` MODIFY COLUMN `refer` bigint;"
9729f4f0   liuzujun   修改邮件默认长度,私聊禁言
269
270
          },
          [3] = {
e9c1df55   liuzujun   活动商品结束清购买记录 修改Ema...
271
              "ALTER TABLE `Email` MODIFY COLUMN `content` VARCHAR(2048);"
9729f4f0   liuzujun   修改邮件默认长度,私聊禁言
272
          },
e9bfa7a2   liuzujun   其他玩家展示界面数据支持, 更新s...
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
      }
  	-- 更新记录表
      local res = mysqlproxy:query("SELECT `value` FROM `autoincrement_set` WHERE `key` = 'db_ver';")
      local ver = res[1].value
      for k, sqls in ipairs(updates) do
          if ver < k then
              skynet.error("do update sql, version:"..k)
              for _, sql in ipairs(sqls) do
                  local r = mysqlproxy:query(sql)
                  if r["errno"] then
                      skynet.error(string.format("%s, err:%s",sql, r["err"]))
                      return
                  end
              end
              mysqlproxy:query(string.format("UPDATE `autoincrement_set` SET `value` = %d WHERE `key` = 'db_ver';", k))
          end
      end
  end
  
314bc5df   zhengshouren   提交服务器初始代码
292
  skynet.start(function ()
0de80321   liuzujun   创建游戏数据库,role对应mys...
293
294
295
296
297
298
  	--local new = redisproxy:hsetnx("autoincrement_set", "server_start", os.date("%Y%m%d", skynet.timex())) == 1
  	--if not new then
  	--	print("server has been initialized...")
  	--	skynet.exit()
  	--	return
  	--end
a5486ede   zhouhaihai   csvdata 修改为 share...
299
300
  	csvdb = require "shared.csvdata"
  	globalCsv = csvdb["GlobalDefineCsv"]
314bc5df   zhengshouren   提交服务器初始代码
301
302
303
304
305
306
  
  	for _, action in ipairs(steps) do
  		print(action.desc .. "start ...")
  		action.handler()
  		print(action.desc .. "finished ...")
  	end
913e070e   liuzujun   添加订单表,全局id定时回写数据库
307
  	initRedisDb()
1279810c   liuzujun   海港贸易任务新增表
308
  	initSeaportTask()		-- 海港任务数据初始化
6136eaca   liuzujun   添加好友表
309
  	loadAllUserInfo()
e9bfa7a2   liuzujun   其他玩家展示界面数据支持, 更新s...
310
      doUpdateSql()       -- 执行更新sql
2f414c31   liuzujun   初始化选择对应游戏数据库
311
  	selectDb()
314bc5df   zhengshouren   提交服务器初始代码
312
313
  	skynet.exit()
  end)