Here is my code
nginx.conf
worker_processes 1;
error_log logs/error.log;
events {
worker_connections 1024;
}
http {
include /vagrant/sso/conf.d/*.conf;
}
sso.conf
lua_package_path "/vagrant/sso/lua.d/?.lua;;";
server {
listen 80;
default_type 'text/plain';
# Set Database variable
set $db_host "127.0.0.1";
set $db_name "lua";
set $db_user "lua_dba";
set $db_pass "myluadatabasepassword";
location / {
content_by_lua "ngx.say('Hello,world!')";
}
location /test {
content_by_lua_file lua.d/test.lua;
}
}
test.lua
-- Test lua file
local user = require "user"
ngx.say(user:get_hash())
— user.lua
local mysql = require "resty.mysql"
local db_host = ngx.var.db_host
local db_name = ngx.var.db_name
local db_user = ngx.var.db_user
local db_pass = ngx.var.db_pass
local db, err = mysql:new()
-- Instantiate a db connection
if not db then
return nil
end
db:set_timeout(1000) -- 1 sec
local ok, err, errno, sqlstate = db:connect{
host = db_host,
port = 3306,
database = db_name,
user = db_user,
password = db_pass,
max_packet_size = 1024 * 1024
}
if not ok then
return nil
end
local _M = {
_VERSION = '0.01'
}
function _M.get_hash()
return db:query("SELECT SHA2(UUID(), 256) AS hash")
end
return _M
I m trying to push the all the function dealing with database into a sub class db.lua in some kid of ORM but i m stuck in first stage it self. I was trying to put the connection routine in db.lua and returning db variable but that also lead to C call boundary error. I them move then in user.lua and again tried to access though test.lua it gave same error.
db.lua
local mysql = require "resty.mysql"
local db, err = mysql:new()
if not db then
-- ngx.say("failed to instantiate mysql: ", err)
return nil
end
db:set_timeout(1000) -- 1 sec
local ok, err, errno, sqlstate = db:connect{
host = ngx.var.db_host,
port = 3306,
database = ngx.var.db_name,
user = ngx.var.db_user,
password = ngx.var.db_pass,
max_packet_size = 1024 * 1024
}
if not ok then
-- ngx.say("failed to connect: ", err, ": ", errno, " ", sqlstate)
return nil
end
return db
Thanks