From 6807522200e07608e0acc826eedfa2469e7ddf0c Mon Sep 17 00:00:00 2001 From: smallfish Date: Wed, 24 Oct 2012 10:42:29 +0800 Subject: [PATCH] update mysql:connect support dsn string --- README.markdown | 17 +++++++++++------ lib/resty/mysql.lua | 24 ++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/README.markdown b/README.markdown index 8b0f927..77654e0 100644 --- a/README.markdown +++ b/README.markdown @@ -48,13 +48,18 @@ Synopsis -- user = "ngx_test", -- password = "ngx_test" } + -- local ok, err, errno, sqlstate = db:connect{ + -- host = "127.0.0.1", + -- port = 3306, + -- database = "ngx_test", + -- user = "ngx_test", + -- password = "ngx_test", + -- max_packet_size = 1024 * 1024 } + local ok, err, errno, sqlstate = db:connect{ - host = "127.0.0.1", - port = 3306, - database = "ngx_test", - user = "ngx_test", - password = "ngx_test", - max_packet_size = 1024 * 1024 } + dsn="host=127.0.0.1;port=3306;database=ngx_test;user=ngx_test;password=ngx_test", + max_packet_size = 1024 * 1024 + } if not ok then ngx.say("failed to connect: ", err, ": ", errno, " ", sqlstate) diff --git a/lib/resty/mysql.lua b/lib/resty/mysql.lua index 78f1063..3f3e0de 100644 --- a/lib/resty/mysql.lua +++ b/lib/resty/mysql.lua @@ -30,6 +30,7 @@ local strbyte = string.byte local strchar = string.char local strfind = string.find local strrep = string.rep +local strsub = string.sub local null = ngx.null local band = bit.band local bxor = bit.bxor @@ -52,6 +53,21 @@ end converters[0x09] = tonumber -- int24 converters[0x0d] = tonumber -- year +local function _split(str, seq) + local list = {} + local pos = 1 + while 1 do + local first, last = strfind(str, seq, pos) + if first then + insert(list, strsub(str, pos, first-1)) + pos = last+1 + else + insert(list, strsub(str, pos)) + break + end + end + return list +end local function _get_byte2(data, i) local a, b = strbyte(data, i, i + 1) @@ -458,6 +474,14 @@ function connect(self, opts) return nil, "not initialized" end + local dsn = opts.dsn + if dsn then + for _, value in pairs(_split(dsn, ";")) do + local _item = _split(value, "=") + opts[_item[1]] = _item[2] + end + end + local max_packet_size = opts.max_packet_size if not max_packet_size then max_packet_size = 1024 * 1024 -- default 1 MB