cloudwu / sproto

Yet another protocol library like google protocol buffers , but simple and fast.
MIT License
942 stars 253 forks source link

sproto 打包的后的二进制数据存数据库问题 #78

Closed aasdpiao closed 6 years ago

aasdpiao commented 6 years ago

需求是 想将存档数据直接通过sproto打包成二进制存入mysql 数据库

但是在存入的时候需要先处理mysql转义字符, 但是取出后数据不能还原了

我不知道是不能这样做呢。还是需要其他处理。

local sp = sproto.parse [[
.build_object{
    build_index 0 : integer
    build_id 1 : integer
    grid_id 2 : integer
    flip 3 : integer
}

.build_data{
    build_objects 0 : *build_object
}
]]

-- 处理mysql转义字符  
local mysqlEscapeMode = "[%z\'\"\\\26\b\n\r\t]"
local mysqlEscapeReplace = {  
    ['\0']='\\0',  
    ['\''] = '\\\'',  
    ['\"'] = '\\\"',  
    ['\\'] = '\\\\',  
    ['\26'] = '\\z',  
    ['\b'] = '\\b',  
    ['\n'] = '\\n',  
    ['\r'] = '\\r',  
    ['\t'] = '\\t',  
    }

local function mysqlEscapeString(s)  
    return string.gsub(s, mysqlEscapeMode, mysqlEscapeReplace) 
end 

build_data = {
        {1001,1001001,2515,1},
        {8004,0,2267,1},
        {8010,0,2268,1},
        {8010,0,2269,1},
        {8014,0,3316,1},
        {4001,4001001,2027,1},
         '''''''
}

local build_dump = {}
build_dump.build_objects = {}
for k,v in pairs(build_data) do
    local build_object = {}
    build_object.build_index = v[1]
    build_object.build_id = v[2]
    build_object.grid_id = v[3]
    build_object.flip = v[4]
    table.insert(build_dump.build_objects,build_object)
end

local code = sp:encode("build_data", build_dump)
code = mysqlEscapeString(code)
local data = sp:decode("build_data", code)
aasdpiao commented 6 years ago

最后通过base64来替换mysql转义来处理可以解决问题。