HomeServer/lualib-src/Server-main/Lib/DB/TableDef.lua

92 lines
2.8 KiB
Lua
Raw Permalink Normal View History

2024-11-20 15:41:09 +08:00
local skynet = require "skynet"
local log = require "Log"
local oo = require "Class"
local TableDef = oo.class()
TableDef.PrimaryKey = {} --主键
TableDef.Index = {} --索引
TableDef.Fields = {} --表字段
--是否存在主键
function TableDef:IsExistPrimaryKey()
if #self.PrimaryKey >= 1 then
return true
else
return false
end
end
--查询是否为主键
function TableDef:IsPrimaryKey( field )
for k, v in pairs( self.PrimaryKey ) do
if field == v.fieldsName then
return true
end
end
return false
end
--获取主键的起始位置
function TableDef:GetKeyStartPosition()
for k1 , v1 in pairs( self.PrimaryKey ) do
for k2 , v2 in pairs( self.Fields ) do
if v1.fieldsName == v2[1] then
return v1.fieldsStartPosition
end
end
end
return 0
end
--获取索引
function TableDef:GetFieldsIndex()
local index = ""
for k , v in pairs( self.Index ) do
index = index .. string.format(", INDEX `%s`(`%s`) USING BTREE" , v.indexName , v.indexFields)
end
return index
end
--获取表所有字段
function TableDef:GetTableFields()
local tableParam = ""
local primaryKey = ""
for k, v in pairs( self.Fields ) do
if self:IsPrimaryKey(v[1]) then
tableParam = tableParam .. string.format("`%s` %s %s auto_increment comment '%s' ," , v[1] , v[3] , v[4] , v[5])
primaryKey = string.format(", primary key (`%s`)" , v[1] )
else
if k == #self.Fields then
--最后一个字段不用加逗号
tableParam = tableParam .. string.format("`%s` %s %s comment '%s'" , v[1] , v[3] , v[4] , v[5])
else
tableParam = tableParam .. string.format("`%s` %s %s comment '%s'," , v[1] , v[3] , v[4], v[5])
end
end
end
tableParam = tableParam..primaryKey
tableParam = tableParam..self:GetFieldsIndex()
return tableParam
end
--获取整个表
function TableDef:GetTable()
local tableParam = "CREATE TABLE if not EXISTS " .. self.TableName
if self:IsExistPrimaryKey() then
tableParam = tableParam .. string.format("( %s using btree)" , self:GetTableFields())
tableParam = tableParam .. string.format("ENGINE = InnoDB AUTO_INCREMENT = %d CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; " , self:GetKeyStartPosition())
else
tableParam = tableParam .. string.format("( %s )" , self:GetTableFields())
tableParam = tableParam .. "ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; "
end
return tableParam
end
--更新表结构
function TableDef:UpdateTable()
end
return TableDef