-- JSON DBC: Database connectivity over a JSON-RPC link. -- Server-side code -- Safe to reload live, but obviously only on the sdmon, and i don't think -- there's a way to do that yet require "jsonrpc/server" db_serv = db_serv or {} function db_serv.make_server(DB_Host, DB_Name, DB_User, DB_Pass, jsonrpc_login_magic) db_serv.mysql_env = assert(luasql.mysql()) db_serv.mysql_conn = assert(db_serv.mysql_env:connect(DB_Name, DB_User, DB_Pass, DB_Host)) local err db_serv.Server, err = JSONRPC.make_server(jsonrpc_port, { -- request methods login=function(conn, userid, magic) if magic == jsonrpc_login_magic then conn.peername = userid..'@'..conn.tcp:GetPeerName() print('login: '..conn.peername) return "ok" end return "invalid magic" end, dbquery=function(conn, qstr, qid) if not conn.peername then return nil, "not authorized" end local nrows=0 local cur,err = db_serv.mysql_conn:execute(qstr) if not cur then return cur,err end if type(cur) == "number" then return cur end local row,err = cur:fetch({}, "a") while row do nrows=nrows+1 conn:notify('dbdata',qid,row,nrows) row,err = cur:fetch(row, "a") end return nrows end, checkpoint=function(conn) -- simple mechanism to ensure an end-to-end flush of write queues return 1 end }, { -- notify methods execute = function(conn, qstr) if not conn.peername then return end -- not logged in, but can't send response in this context local ok,err = db_serv.mysql_conn:execute(qstr) if not ok then log.error("error in async query execution("..tostring(qstr).."): "..err) end end }, function(conn) -- connect callback --print('(connection established to '..conn.tcp:GetPeerName()..')') end, function(conn) -- disconnect callback -- neat, tcp is basically bunk at this point because the connection is closed! print(conn.peername..' disconnected') conn.peername = nil end) if not db_serv.Server then return nil, err end return db_serv.Server end