diff --git a/lib/resty/mysql.lua b/lib/resty/mysql.lua index 8efece9..a629daa 100644 --- a/lib/resty/mysql.lua +++ b/lib/resty/mysql.lua @@ -23,6 +23,12 @@ local error = error local tonumber = tonumber +local ok, new_tab = pcall(require, "table.new") +if not ok then + new_tab = function (narr, nrec) return {} end +end + + local _M = { _VERSION = '0.13' } @@ -43,7 +49,7 @@ local mt = { __index = _M } -- mysql field value type converters -local converters = {} +local converters = new_tab(0, 8) for i = 0x01, 0x05 do -- tiny, short, long, float, double @@ -127,8 +133,8 @@ end local function _dump(data) - local bytes = {} local len = #data + local bytes = new_tab(len, 0) for i = 1, len do bytes[i] = strbyte(data, i) end @@ -137,8 +143,8 @@ end local function _dumphex(data) - local bytes = {} local len = #data + local bytes = new_tab(len, 0) for i = 1, len do bytes[i] = tohex(strbyte(data, i), 2) end @@ -154,8 +160,8 @@ local function _compute_token(password, scramble) local stage1 = sha1(password) local stage2 = sha1(stage1) local stage3 = sha1(scramble .. stage2) - local bytes = {} local n = #stage1 + local bytes = new_tab(n, 0) for i = 1, n do bytes[i] = strchar(bxor(strbyte(stage3, i), strbyte(stage1, i))) end @@ -283,7 +289,7 @@ end local function _parse_ok_packet(packet) - local res = {} + local res = new_tab(0, 5) local pos res.affected_rows, pos = _from_length_coded_bin(packet, 2) @@ -350,7 +356,7 @@ end local function _parse_field_packet(data) - local col = {} + local col = new_tab(0, 2) local catalog, db, table, orig_table, orig_name, charsetnr, length local pos catalog, pos = _from_length_coded_str(data, 1) @@ -391,9 +397,14 @@ end local function _parse_row_data_packet(data, cols, compact) - local row = {} local pos = 1 local ncols = #cols + local row + if compact then + row = new_tab(ncols, 0) + else + row = new_tab(0, ncols) + end for i = 1, ncols do local value value, pos = _from_length_coded_str(data, pos) @@ -714,7 +725,7 @@ end _M.send_query = send_query -local function read_result(self) +local function read_result(self, est_nrows) if self.state ~= STATE_COMMAND_SENT then return nil, "cannot read result in the current context: " .. self.state end @@ -760,7 +771,7 @@ local function read_result(self) --print("field count: ", field_count) - local cols = {} + local cols = new_tab(field_count, 0) for i = 1, field_count do local col, err, errno, sqlstate = _recv_field_packet(self) if not col then @@ -784,7 +795,7 @@ local function read_result(self) local compact = self.compact - local rows = {} + local rows = new_tab(est_nrows or 4, 0) local i = 0 while true do --print("reading a row") @@ -824,13 +835,13 @@ end _M.read_result = read_result -function _M.query(self, query) +function _M.query(self, query, est_nrows) local bytes, err = send_query(self, query) if not bytes then return nil, "failed to send query: " .. err end - return read_result(self) + return read_result(self, est_nrows) end