Merge pull request #366 from fztcjjl/master

add a callback for mysql auth
This commit is contained in:
云风
2015-10-28 20:49:44 +08:00
2 changed files with 15 additions and 10 deletions

13
lualib/mysql.lua Executable file → Normal file
View File

@@ -418,7 +418,7 @@ local function _recv_auth_resp(self)
end end
local function _mysql_login(self,user,password,database) local function _mysql_login(self,user,password,database,on_connect)
return function(sockchannel) return function(sockchannel)
local packet, typ, err = sockchannel:response( _recv_decode_packet_resp(self) ) local packet, typ, err = sockchannel:response( _recv_decode_packet_resp(self) )
@@ -490,7 +490,10 @@ local function _mysql_login(self,user,password,database)
local packet_len = #req local packet_len = #req
local authpacket=_compose_packet(self,req,packet_len) local authpacket=_compose_packet(self,req,packet_len)
return sockchannel:request(authpacket,_recv_auth_resp(self)) sockchannel:request(authpacket,_recv_auth_resp(self))
if on_connect then
on_connect(self)
end
end end
end end
@@ -626,7 +629,7 @@ local function _query_resp(self)
end end
end end
function _M.connect( opts) function _M.connect(opts)
local self = setmetatable( {}, mt) local self = setmetatable( {}, mt)
@@ -645,11 +648,11 @@ function _M.connect( opts)
local channel = socketchannel.channel { local channel = socketchannel.channel {
host = opts.host, host = opts.host,
port = opts.port or 3306, port = opts.port or 3306,
auth = _mysql_login(self,user,password,database ), auth = _mysql_login(self,user,password,database,opts.on_connect),
} }
self.sockchannel = channel
-- try connect first only once -- try connect first only once
channel:connect(true) channel:connect(true)
self.sockchannel = channel
return self return self

View File

@@ -70,21 +70,23 @@ local function test3( db)
end end
skynet.start(function() skynet.start(function()
local db=mysql.connect{ local function on_connect(db)
db:query("set charset utf8");
end
local db=mysql.connect({
host="127.0.0.1", host="127.0.0.1",
port=3306, port=3306,
database="skynet", database="skynet",
user="root", user="root",
password="1", password="1",
max_packet_size = 1024 * 1024 max_packet_size = 1024 * 1024,
} on_connect = on_connect
})
if not db then if not db then
print("failed to connect") print("failed to connect")
end end
print("testmysql success to connect to mysql server") print("testmysql success to connect to mysql server")
db:query("set names utf8")
local res = db:query("drop table if exists cats") local res = db:query("drop table if exists cats")
res = db:query("create table cats " res = db:query("create table cats "
.."(id serial primary key, ".. "name varchar(5))") .."(id serial primary key, ".. "name varchar(5))")