Blame view

src/shared/ModelBaseMysql.lua 16.8 KB
0de80321   liuzujun   创建游戏数据库,role对应mys...
1
2
3
4
  local ModelBaseMysql = class("ModelBaseMysql")
  ModelBaseMysql.key = "key"
  ModelBaseMysql.schema = {}
  
e84a1beb   liuzujun   gm后台查询日志,公告相关协议
5
6
  local mysqlproxy = require "shared.mysqlproxy"
  
0de80321   liuzujun   创建游戏数据库,role对应mys...
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
  local string_format = string.format
  local table_insert = table.insert
  local table_unpack = table.unpack
  local assert = assert
  local next = next
  local ipairs = ipairs
  local pairs = pairs
  local tostring = tostring
  local tonumber = tonumber
  local mysqlproxy = mysqlproxy
  
  local function filterProperties(properties, filter)
      for i, field in ipairs(filter) do
          properties[field] = nil
      end
  end
  
  function ModelBaseMysql:ctor(properties)
      self.cacheFields = {} --缓存字段 不更新数据库的字段
  
      self[self.class.key .. "_"] = properties[self.class.key] --数据库key
      properties[self.class.key] = nil
  
      if not self:isValidKey() then
          print(string_format("%s [%s:key] should be give in new(ctor)", tostring(self), self.class.__cname))
          return
      end
  
      if type(properties) ~= "table" then properties = {} end
      self:loadProperties(properties)  --缺少的域将设置默认值
      self:getPriKey()
  end
  
0de80321   liuzujun   创建游戏数据库,role对应mys...
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
  --[[--
  
  返回对象的 ID 值。
  
  **Returns:**
  
  -   ID 
  
  ]]
  function ModelBaseMysql:getKey()
      local id = self[self.class.key .. "_"]
      assert(id ~= nil, string_format("%s [%s:getKey()] Invalid key", tostring(self), self.class.__cname))
      return id
  end
  
  function ModelBaseMysql:getPriKey()
      for k, v in pairs(self.class.schema) do
          local objType, def, keyType, length = table_unpack(v)
2ca93972   liuzujun   添加邮件表
58
          if keyType == "pri" or keyType == "pri_auto" then
0de80321   liuzujun   创建游戏数据库,role对应mys...
59
              self.pri_key = k
fa992c94   liuzujun   添加daily,diner,act...
60
              break
0de80321   liuzujun   创建游戏数据库,role对应mys...
61
62
63
64
65
66
67
68
69
          end
      end
  end
  
  function ModelBaseMysql:load(properties)
      if not self:isValidKey() then
          print(string_format("%s [%s:id] should be set before load", tostring(self), self.class.__cname))
          return false
      end
a12bfcce   liuzujun   添加英雄表
70
      local load = false
0de80321   liuzujun   创建游戏数据库,role对应mys...
71
      if not properties then
913e070e   liuzujun   添加订单表,全局id定时回写数据库
72
          properties = mysqlproxy:query(string_format("SELECT * from `%s` where `%s` = %s;", self.class.__cname, self.pri_key, self:getKey()))
a12bfcce   liuzujun   添加英雄表
73
          load = true
0de80321   liuzujun   创建游戏数据库,role对应mys...
74
75
76
      end
      if not next(properties) then return false end
  
a12bfcce   liuzujun   添加英雄表
77
78
79
      local data = load and properties[1] or properties
  
      self:loadProperties(data)
0de80321   liuzujun   创建游戏数据库,role对应mys...
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
  
      self:onLoad()
  
      return true
  end
  
  --创建model对应的redis数据, 必须已经设置了ID
  function ModelBaseMysql:create()
      if not self:isValidKey() then
          print(string_format("%s [%s:key] should be set before create", tostring(self), self.class.__cname))
          return nil
      end
  
      self:save()
      self:onCreate()
  
      return self
  end
  
  -- save 忽略 缓存配置
  function ModelBaseMysql:save()
      local redisProperties = self:getProperties()
  
      local params = {}
      for fieldName, value in pairs(redisProperties) do
          local propname = fieldName .. "_"
          if self.class.schema[fieldName][1] == "table" then
              if not next(self[propname]) then 
                  params[fieldName] = "NULL"
              else
6af09a92   liuzujun   mysql二进制数据加上quote...
110
111
112
                  local result = mysqlproxy:quote_sql_str(MsgPack.pack(self[propname]))
                  --params[fieldName] = "'" .. MsgPack.pack(self[propname]) .. "'"
                  params[fieldName] = result
0de80321   liuzujun   创建游戏数据库,role对应mys...
113
114
              end
          elseif self.class.schema[fieldName][1] == "string" then
6af09a92   liuzujun   mysql二进制数据加上quote...
115
116
117
              local result = mysqlproxy:quote_sql_str(self[propname])
              --params[fieldName] = "'" .. self[propname] .. "'"
              params[fieldName] = result
0de80321   liuzujun   创建游戏数据库,role对应mys...
118
119
120
121
122
123
          else
              params[fieldName] = self[propname]
          end
      end
      if next(params) then
          -- insert update
913e070e   liuzujun   添加订单表,全局id定时回写数据库
124
          local sql = "INSERT INTO `%s` (%s) VALUES (%s) ON DUPLICATE KEY UPDATE %s;"
0de80321   liuzujun   创建游戏数据库,role对应mys...
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
          local tbName = self.class.__cname
          local key_list = ""
          local value_list = ""
          local update_list = ""
          for k, v in pairs(params) do
              if key_list ~= "" then
                 key_list = key_list .. ","
              end
              if value_list ~= "" then
                 value_list = value_list .. ","
              end
              if update_list ~= "" then
                 update_list = update_list .. ","
              end
  
fa992c94   liuzujun   添加daily,diner,act...
140
              key_list = key_list .. "`" .. k .. "`"
0de80321   liuzujun   创建游戏数据库,role对应mys...
141
              value_list = value_list .. v
fa992c94   liuzujun   添加daily,diner,act...
142
              update_list = update_list .. "`" .. k .. "`=" .. v
0de80321   liuzujun   创建游戏数据库,role对应mys...
143
144
          end
          sql = string_format(sql, tbName, key_list, value_list, update_list)
6af09a92   liuzujun   mysql二进制数据加上quote...
145
          local res = mysqlproxy:query(sql)
6136eaca   liuzujun   添加好友表
146
147
          if res["errno"] then
              skynet.error(sql)
01be2d78   liuzujun   修改mysql链接断开重连的bug
148
              skynet.error(res["err"])
6136eaca   liuzujun   添加好友表
149
          end
0de80321   liuzujun   创建游戏数据库,role对应mys...
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
      end
  end
  
  --[[--
  
  确定对象是否设置了有效的 key
  
  ]]
  function ModelBaseMysql:isValidKey()
      local propname = self.class.key .. "_"
      local key = self[propname]
      return type(key) == "string" and key ~= ""
  end
  
  --[[--
  
  加载对象的属性进内存。
  NOTE: 如果properties缺少schema中的域, 将用默认值来填充
  
  **Parameters:**
  
  -   properties: 包含属性值的数组
  
  ]]
  function ModelBaseMysql:loadProperties(properties)
      assert(type(properties) == "table", "Invalid properties")
      for field, schema in pairs(self.class.schema) do
          local typ, def = table_unpack(schema)
          local propname = field .. "_"
  
          if typ == "table" and type(properties[field]) == "string" then
              properties[field] = MsgPack.unpack(properties[field])
          end
  
          local val = properties[field] or def
          if val ~= nil then
              if typ == "number" then val = tonumber(val) end
              assert(type(val) == typ,
                 string_format("%s [%s:loadProperties()] Type mismatch, %s expected %s, actual is %s",
                                   tostring(self), self.class.__cname, field, typ, type(val)))
              self[propname] = val
          end
      end
  end
  
  --[[--
  
  取得对象的属性值。
  
  **Parameters:**
  
  -   fields: 要取得哪些属性的值,如果未指定该参数,则返回 fields 中设定的属性
  -   filter: 要从结果中过滤掉哪些属性,如果未指定则不过滤
  
  **Returns:**
  
  -   包含属性值的数组
  
  ]]
  function ModelBaseMysql:getProperties(fields, filter)
      local schema = self.class.schema
      if type(fields) ~= "table" then fields = table.keys(self.class.schema) end
  
      local properties = {}
      for i, field in ipairs(fields) do
          local propname = field .. "_"
          local typ = schema[field][1]
          local val = self[propname]
          assert(type(val) == typ,
                 string_format("%s [%s:getProperties()] Type mismatch, %s expected %s, actual is %s",
                                   tostring(self), self.class.__cname, field, typ, type(val)))
          properties[field] = val
      end
  
      if type(filter) == "table" then
          filterProperties(properties, filter)
      end
  
      return properties
  end
  
  function ModelBaseMysql:getProperty(property)
      if type(property) ~= "string" then return nil end
      if not self.class.schema[property] then return nil end
      return self:getProperties({property})[property]
  end
  
6136eaca   liuzujun   添加好友表
237
  function ModelBaseMysql:setProperty(property, value, forceSave)
0de80321   liuzujun   创建游戏数据库,role对应mys...
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
      if not self.class.schema[property] then
          print(string_format("%s [%s:setProperty()] Invalid property : %s",
              tostring(self), self.class.__cname, property))
          return
      end
  
      local typ, def = table_unpack(self.class.schema[property])
      local propname = property .. "_"
  
      if typ == "number" then value = tonumber(value) end
      if typ == "table" and not value then
          value = self[propname] -- table 可以用自己的缓冲
      end
      assert(type(value) == typ,
         string_format("%s [%s:setProperties()] Type mismatch, %s expected %s, actual is %s",
           tostring(self), self.class.__cname, property, typ, type(value)))
0de80321   liuzujun   创建游戏数据库,role对应mys...
254
  
6136eaca   liuzujun   添加好友表
255
256
257
258
259
260
261
262
263
264
265
      if typ == "number" or typ == "string" then
          if self[propname] == value then
              return
          end
      end
      self[propname] = value
      --self:save()
      self.cacheFields[property] = self[propname]
      if forceSave then
          self:update()
      end
0de80321   liuzujun   创建游戏数据库,role对应mys...
266
267
  end
  
6136eaca   liuzujun   添加好友表
268
  function ModelBaseMysql:setProperties(fields, forceSave)
0de80321   liuzujun   创建游戏数据库,role对应mys...
269
270
271
272
273
274
275
276
277
278
279
280
281
282
      for property, value in pairs(fields) do
           if not self.class.schema[property] then
              print(string_format("%s [%s:setProperty()] Invalid property : %s",
                  tostring(self), self.class.__cname, property))
          else
              local typ, def = table_unpack(self.class.schema[property])
              local propname = property .. "_"
              if typ == "number" then value = tonumber(value) end
              if typ == "table" and not value then
                  value = self[propname] -- table 可以用自己的缓冲
              end
              assert(type(value) == typ,
                 string_format("%s [%s:setProperties()] Type mismatch, %s expected %s, actual is %s",
                   tostring(self), self.class.__cname, property, typ, type(value)))
0de80321   liuzujun   创建游戏数据库,role对应mys...
283
  
6136eaca   liuzujun   添加好友表
284
              if typ == "number" or typ == "string" then
ab57e0ab   liuzujun   修改数据存储bug
285
286
287
                  if self[propname] ~= value then
                      self[propname] = value
                      self.cacheFields[property] = self[propname]
6136eaca   liuzujun   添加好友表
288
                  end
899d9b8a   liuzujun   modelbasemysql保存bug
289
290
291
              else
                  self[propname] = value
                  self.cacheFields[property] = self[propname]
0de80321   liuzujun   创建游戏数据库,role对应mys...
292
              end
0de80321   liuzujun   创建游戏数据库,role对应mys...
293
294
          end
      end
6136eaca   liuzujun   添加好友表
295
296
297
298
      if forceSave then
          self:update()
      end
      --self:save()
0de80321   liuzujun   创建游戏数据库,role对应mys...
299
300
  end
  
6136eaca   liuzujun   添加好友表
301
  function ModelBaseMysql:incrProperty(property, value, forceSave)
0de80321   liuzujun   创建游戏数据库,role对应mys...
302
303
304
305
306
307
308
309
310
      if not self.class.schema[property] then
          print(string_format("%s [%s:setProperty()] Invalid property : %s",
              tostring(self), self.class.__cname, property))
          return
      end
  
      local typ, def = table_unpack(self.class.schema[property])
      local propname = property .. "_"
  
6136eaca   liuzujun   添加好友表
311
      if typ == "table" or typ == "string" then return end
0de80321   liuzujun   创建游戏数据库,role对应mys...
312
313
      if typ == "number" then value = tonumber(value) end
  
6136eaca   liuzujun   添加好友表
314
      self:setProperty(property, self[propname] + value, forceSave)
0de80321   liuzujun   创建游戏数据库,role对应mys...
315
316
317
318
319
320
321
322
  end
  
  function ModelBaseMysql:onLoad()
  end
  
  function ModelBaseMysql:onCreate()
  end
  
fa992c94   liuzujun   添加daily,diner,act...
323
324
325
326
327
  function ModelBaseMysql:checkKeyExists(key)
      local res = mysqlproxy:query(string_format("SELECT * FROM `%s` WHERE `%s` = %s", self.class.__cname, self.pri_key, key))
      return next(res)
  end
  
0de80321   liuzujun   创建游戏数据库,role对应mys...
328
329
330
  function ModelBaseMysql:checkTableSchema()
      -- 1.检测是否表存在
      local typeMap = {
2ca93972   liuzujun   添加邮件表
331
          number = {"int", 0},
0de80321   liuzujun   创建游戏数据库,role对应mys...
332
          string = {"varchar", "", 128},
a12bfcce   liuzujun   添加英雄表
333
334
          table = {"blob", "NULL"},
          pri = {"bigint", 0},
0de80321   liuzujun   创建游戏数据库,role对应mys...
335
336
337
338
339
      }
      local tbName = self.class.__cname
      local create_sql = [[
  		CREATE TABLE IF NOT EXISTS `%s` (
              %s
a12bfcce   liuzujun   添加英雄表
340
              PRIMARY KEY (`%s`)%s
0de80321   liuzujun   创建游戏数据库,role对应mys...
341
342
  			) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
      ]]
a12bfcce   liuzujun   添加英雄表
343
344
      local index_tpl_str = [[,INDEX `%s_Index` (`%s`)]]
      
0de80321   liuzujun   创建游戏数据库,role对应mys...
345
346
347
348
349
350
      local alter_sql = [[
  		ALTER TABLE `%s` ADD COLUMN (
              %s
  		) ;
      ]]
      local field_tpl_str = "`%s` %s%s DEFAULT %s"
2ca93972   liuzujun   添加邮件表
351
      local auto_increment_str = "`%s` %s NOT NULL AUTO_INCREMENT"
0de80321   liuzujun   创建游戏数据库,role对应mys...
352
353
      local field_str = ""
  
2ca93972   liuzujun   添加邮件表
354
      local res = mysqlproxy:query("desc `".. tbName .. "`;")
a12bfcce   liuzujun   添加英雄表
355
      local keyList = {}
0de80321   liuzujun   创建游戏数据库,role对应mys...
356
357
358
359
      if res["err"] then -- 表不存在
          local schema = {}
          for k, v in pairs(self.class.schema) do
              local keyType = v[3]
2ca93972   liuzujun   添加邮件表
360
              if keyType == "pri" or keyType == "pri_auto" then
0de80321   liuzujun   创建游戏数据库,role对应mys...
361
362
363
                  self.pri_key = k
                  table_insert(schema, 1, {k, v})
              else
a12bfcce   liuzujun   添加英雄表
364
365
366
                  if keyType == "index" then
                      table_insert(keyList, k)
                  end
0de80321   liuzujun   创建游戏数据库,role对应mys...
367
368
369
370
371
372
                  table_insert(schema, {k, v})
              end
          end
          for _, tbl in ipairs(schema) do
              local k, v = tbl[1], tbl[2]
              local objType, def, keyType, length = table_unpack(v)
2ca93972   liuzujun   添加邮件表
373
              local isAutoPriKey = false
0de80321   liuzujun   创建游戏数据库,role对应mys...
374
              assert(typeMap[objType], string_format("schema invalid type, %s, %s", tbName, k))
a12bfcce   liuzujun   添加英雄表
375
376
              -- 主键使用bigint存储
              if keyType == "pri" then objType = "pri" end
2ca93972   liuzujun   添加邮件表
377
378
379
380
381
382
              if keyType == "pri" or keyType == "pri_auto" then
                  objType = "pri"
                  if keyType == "pri_auto" then
                      isAutoPriKey = true
                  end
              end
0de80321   liuzujun   创建游戏数据库,role对应mys...
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
  
              local info = typeMap[objType]
              local suffix = ""
              local fieldType = info[1]
              if objType == "table" or not def or def == "" then def = info[2] end
              if type(def) == "string" and def ~= "NULL" then def = "'" .. def .. "'" end
              if info[3] and not length then length = info[3] end
              -- 设置字段长度
              if info[3] then suffix = string.format("(%d)", length) end
              -- 很长的string使用blob
              if  keyType == "blob" then 
                  fieldType = keyType
                  suffix = ""
                  def = "NULL"
              end
  
2ca93972   liuzujun   添加邮件表
399
400
401
402
403
              if not isAutoPriKey then
                  field_str = field_str .. string.format(field_tpl_str..",", k, fieldType, suffix, def)
              else
                  field_str = field_str .. string.format(auto_increment_str..",", k, fieldType)
              end
0de80321   liuzujun   创建游戏数据库,role对应mys...
404
405
406
          end
  
          assert(self.pri_key, string_format("table not include primary key, [%s]", tbName))
a12bfcce   liuzujun   添加英雄表
407
408
409
410
          local index_key_str = ""
          for _, k in ipairs(keyList) do
              index_key_str = index_key_str .. string_format(index_tpl_str, k, k)
          end
0de80321   liuzujun   创建游戏数据库,role对应mys...
411
          -- 创建表格
2ca93972   liuzujun   添加邮件表
412
          print(string_format(create_sql, tbName, field_str, self.pri_key, index_key_str))
a12bfcce   liuzujun   添加英雄表
413
          mysqlproxy:query(string_format(create_sql, tbName, field_str, self.pri_key, index_key_str))
0de80321   liuzujun   创建游戏数据库,role对应mys...
414
415
416
417
418
419
420
421
      else    -- 检测是否有添加新字段
          local addCol = {}
          local curCols = {}
          for _, col in ipairs(res) do
              curCols[col["Field"]] = 1
          end
          for k, v in pairs(self.class.schema) do
              local objType, def, keyType, length = table_unpack(v)
0de80321   liuzujun   创建游戏数据库,role对应mys...
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
              if not curCols[k] then
                  print(string_format("table [%s] add new column [%s]", tbName, k))
                  assert(typeMap[objType], string_format("schema invalid type, [%s], [%s]", tbName, k))
  
                  local info = typeMap[objType]
                  local suffix = ""
                  local fieldType = info[1]
                  if objType == "table" or not def or def == "" then def = info[2] end
                  if type(def) == "string" and def ~= "NULL" then def = "'" .. def .. "'" end
                  if info[3] and not length then length = info[3] end
                  -- 设置字段长度
                  if info[3] then suffix = string.format("(%d)", length) end
                  -- 很长的string使用blob
                  if  keyType == "blob" then 
                      fieldType = keyType
                      suffix = ""
                      def = "NULL"
                  end
                  local sep = ","
                  if field_str == "" then
                      sep = ""
                  end
                  field_str = field_str .. string.format(sep..field_tpl_str, k, fieldType, suffix, def)
              end
          end
          -- 添加新列
          if field_str ~= "" then
              mysqlproxy:query(string_format(alter_sql, tbName, field_str))
          end
      end
  
  end
  
6136eaca   liuzujun   添加好友表
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
  function  ModelBaseMysql:loadFields(fields)
      if not self:isValidKey() then
          print(string_format("%s [%s:id] should be set before load", tostring(self), self.class.__cname))
          return
      end
      if not next(fields) then
          return
      end
      local final = {}
      for _, v in ipairs(fields) do
          table.insert(final, '`'..v..'`')
      end
      local field_list = table.concat(final, ",")
      local res = mysqlproxy:query(string_format("SELECT %s from `%s` where `%s` = %s;", field_list, self.class.__cname, self.pri_key, self:getKey()))
      if res["errno"] then
          return
      end
  
      return res[1]
  end
  
  function ModelBaseMysql:update()
      if next(self.cacheFields) then
          self:updateFields(self.cacheFields)
          self.cacheFields = {}
      end
  end
  
  function ModelBaseMysql:updateFields(fields)
      local params = {}
      for field, value in pairs(fields) do
          if self.class.schema[field][1] == "table" then
              if next(value) then 
                  local result = mysqlproxy:quote_sql_str(MsgPack.pack(value))
                  params[field] = result
70427331   zhangqijia   fix: 解决的bug是每天上线都...
490
491
              else
                  params[field] = mysqlproxy:quote_sql_str(MsgPack.pack({}))
6136eaca   liuzujun   添加好友表
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
              end
          elseif self.class.schema[field][1] == "string" then
              local result = mysqlproxy:quote_sql_str(value)
              params[field] = result
          else
              params[field] = value 
          end
      end
      if next(params) then
          local sql = "UPDATE `%s` SET %s WHERE `%s` = %s;"
          local tbName = self.class.__cname
          local tmp = {}
          for k, v in pairs(params) do
              table.insert(tmp, '`' .. k .. '` = ' .. v)
          end
          sql = string_format(sql, tbName, table.concat(tmp, ","), self.pri_key, self:getKey())
          local res = mysqlproxy:query(sql)
          if res["errno"] then
7104ee66   liuzujun   重复过新手bug, daily错误...
510
511
              skynet.error("error sql:"..sql)
              skynet.error("error str:"..res["err"])
6136eaca   liuzujun   添加好友表
512
              return false
29c70fba   liuzujun   添加更新sql affect ro...
513
514
515
516
517
          else
              if (res["affected_rows"] or -1) == 0 then
                  skynet.error("affected row = 0")
                  skynet.error("error sql:"..sql)
              end
6136eaca   liuzujun   添加好友表
518
519
520
521
522
          end
      end
      return true
  end
  
0de80321   liuzujun   创建游戏数据库,role对应mys...
523
  return ModelBaseMysql