使用orm进行数据表封装,并编写和调试接口相关函数错误问题和相关内容的修改

This commit is contained in:
wanglei 2025-10-25 14:33:27 +08:00
parent f694593436
commit 48d0133a79
4 changed files with 97 additions and 81 deletions

View File

@ -15,10 +15,23 @@
local User = require("model.user") local User = require("model.user")
local user = User.find("1") --获取数据表中的记录数
ngx.say(user) local code, res = User:count()
local userPages = User:paginate(1) --ngx.say(res)
ngx.say(userPages)
--查询表中id为1的数据记录
code, res = User:find("1")
--查询表中的所有记录
code, res = User:all()
for _, row in ipairs(res) do
for key, value in pairs(row) do
ngx.say(key .. ":" .. tostring(value))
end
end
--local code, userPages = User:paginate(1)
--ngx.say(userPages)
--获取请求参数的键值和数据值 --获取请求参数的键值和数据值
--local cjson = require("cjson") --local cjson = require("cjson")

View File

@ -12,15 +12,14 @@ local mt = { __index = _M }
@return bool, db_context, err @return bool, db_context, err
--]] --]]
function _M:get_connection() function _M:get_connection()
local code = 0
if ngx.ctx[self.db_type] then if ngx.ctx[self.db_type] then
-- if write before read, make sure write read connection the same -- if write before read, make sure write read connection the same
if ngx.ctx[WRITE] then if ngx.ctx[WRITE] then
return ngx.ctx[WRITE], nil return code, ngx.ctx[WRITE]
end end
return ngx.ctx[self.db_type], nil return code, ngx.ctx[self.db_type]
end end
local code = 0
-- 创建一个新的连接 -- 创建一个新的连接
local conn = pgmoon.new({ local conn = pgmoon.new({
host = self.host, -- postgres host host = self.host, -- postgres host
@ -29,13 +28,14 @@ function _M:get_connection()
password = self.password, -- postgres password password = self.password, -- postgres password
database = self.database database = self.database
}); });
conn.set_timeout(self.timeout or 1000) --conn.set_timeout(self.timeout or 1000)
---- 连接到数据库 ---- 连接到数据库
local ok, err = conn:connect() local ok, err = conn:connect()
if not ok then if not ok then
print("Connection failed: " .. err) print("Connection failed: " .. err)
code = 0x000002 code = 0x000002
end end
ngx.log(ngx.INFO, 'Connection success')
--ngx.say("Connection success") --ngx.say("Connection success")
ngx.ctx[self.db_type] = conn ngx.ctx[self.db_type] = conn
return code,conn return code,conn
@ -63,18 +63,18 @@ end
@return bool, data, err @return bool, data, err
--]] --]]
function _M.db_query(self, sql) function _M.db_query(self, sql)
local db, err = self:get_connection() local code, conn = self:get_connection()
if err ~= nil then if code ~= 0 then
return nil, err return code,nil
end end
local res, errcode, sqlstate ngx.log(ngx.INFO, 'begin db query :' .. sql)
res, err, errcode, sqlstate = db:query(sql) -- 执行查询
local res, err = conn:query(sql)
if not res then if not res then
ngx.log(ngx.ERR, err, errcode, sqlstate) ngx.log(ngx.ERR, 'Query failed:' .. sql)
return nil, err return 2,nil
end end
return 0, res
return res, nil
end end
function _M.new(self, opts) function _M.new(self, opts)
@ -85,7 +85,7 @@ function _M.new(self, opts)
password = opts.password or '', password = opts.password or '',
database = opts.database or 'postgres', database = opts.database or 'postgres',
--charset = opts.charset or 'utf8mb4', --charset = opts.charset or 'utf8mb4',
--timeout = opts.timeout, --timeout = opts.timeout or 1000,
--max_packet_size = 1024 * 1024, --max_packet_size = 1024 * 1024,
db_pool_timeout = opts.pool_timeout or 1000, db_pool_timeout = opts.pool_timeout or 1000,
db_pool_size = opts.pool_size or 1000, db_pool_size = opts.pool_size or 1000,

View File

@ -94,7 +94,7 @@ end
local function set_cookie(key, value, expires) local function set_cookie(key, value, expires)
local config = require("config.app") local config = require("config.app")
local cookie, err = require("lib.cookie"):new() local cookie, err = require("util.cookie"):new()
if not cookie then if not cookie then
ngx.log(ngx.ERR, err) ngx.log(ngx.ERR, err)
return false, err return false, err
@ -118,7 +118,7 @@ local function set_cookie(key, value, expires)
end end
local function get_cookie(key) local function get_cookie(key)
local cookie, err = require("lib.cookie"):new() local cookie, err = require("util.cookie"):new()
if not cookie then if not cookie then
ngx.log(ngx.ERR, err) ngx.log(ngx.ERR, err)
return false return false
@ -127,7 +127,7 @@ local function get_cookie(key)
end end
local function get_local_time() local function get_local_time()
local config = require("config.app") local config = require("config.config")
local time_zone = ngx.re.match(config.time_zone, "[0-9]+") local time_zone = ngx.re.match(config.time_zone, "[0-9]+")
if time_zone == nil then if time_zone == nil then
local err = "not set time zone or format error, time zone should look like `+8:00` current is: " .. config.time_zone local err = "not set time zone or format error, time zone should look like `+8:00` current is: " .. config.time_zone

View File

@ -8,8 +8,6 @@ local table_remove = helpers.table_remove
local _M = {} local _M = {}
local mt = { __index = _M }
local WRITE = 'WRITE' local WRITE = 'WRITE'
local READ = 'READ' local READ = 'READ'
@ -125,27 +123,29 @@ end
function _M:find(id,column) function _M:find(id,column)
if self.query_sql ~= nil then if self.query_sql ~= nil then
ngx.log(ngx.ERR, 'cannot use find() with other query sql') ngx.log(ngx.ERR, 'cannot use find() with other query sql')
return nil return 1, nil
end end
column = column or 'id' column = column or 'id'
id = transform_value(id) id = transform_value(id)
ngx.log(ngx.INFO, 'table name :' .. self.table)
local sql = 'select * from '..self.table..' where '..column..'='..id..' limit 1' local sql = 'select * from '..self.table..' where '..column..'='..id..' limit 1'
local res = self:query(sql, READ) ngx.log(ngx.INFO, 'query sql:', sql)
local code, res = self:query(sql, READ)
if table.getn(res) > 0 then if table.getn(res) > 0 then
ngx.log(ngx.INFO, 'query record count:', table.getn(res))
res = self:make_relations(res) res = self:make_relations(res)
return res[1] return code, res
else
return false
end end
return code, nil
end end
function _M:all() function _M:all()
if self.query_sql ~= nil then if self.query_sql ~= nil then
ngx.log(ngx.ERR, 'cannot use all() with other query sql ', self.query_sql) ngx.log(ngx.ERR, 'cannot use all() with other query sql ', self.query_sql)
return nil return 2, nil
end end
local res = self:query('select * from '..self.table, READ) local code, res = self:query('select * from \"'..self.table..'\"', READ)
return self:make_relations(res) return code, self:make_relations(res)
end end
--组装sql语句条件为and相关的字段 --组装sql语句条件为and相关的字段
@ -187,18 +187,17 @@ end
--获取数据表中记录的数量 --获取数据表中记录的数量
function _M:count() function _M:count()
local sql = self.query_sql local sql = ""
if not sql then if self.query_sql ~= nil then
sql = 'select count(*) from '..self.table sql = 'select count(*) from \"'..self.table..'\" '..self.query_sql
else else
sql = 'select count(*) from '..self.table..' '..self.query_sql sql = 'select count(*) from \"'..self.table.."\""
end end
local res = self:query(sql, READ) local code, res = self:query(sql, READ)
if table.getn(res) > 0 then if table.getn(res) > 0 then
return tonumber(res[1]['count(*)']) return code, tonumber(res[1]['count'])
else
return 0
end end
return code, nil
end end
-- params: (option)int num -- params: (option)int num
@ -222,10 +221,10 @@ function _M:get(num)
end end
--根据数据模型中的 --根据数据模型中的
function _M:paginate(page_num, per_page) function _M:paginate(page_num, page_size)
page_num = page_num or 1 page_num = page_num or 1
per_page = per_page or config.per_page page_size = page_size or 10
local sql, count_sql, total local sql, count_sql, total, code
local data={ local data={
data = {}, data = {},
next_page = 1, next_page = 1,
@ -233,25 +232,24 @@ function _M:paginate(page_num, per_page)
total = 0 total = 0
} }
if not self.query_sql then if not self.query_sql then
sql = 'select * from '..self.table..' limit '..per_page*page_num..','..per_page sql = 'select * from \"'..self.table..'\" limit '..page_num..' offset '..page_size
count_sql = 'select count(*) from '..self.table count_sql = 'select count(*) from \"'..self.table..'\"'
else else
sql = 'select * from '..self.table .. ' '..self.query_sql .. ' limit '..per_page*(page_num-1)..','..per_page sql = 'select * from \"'..self.table .. '\" '..self.query_sql .. ' limit '..page_num..' offset '..page_size
count_sql = 'select count(*) from '..self.table..' '..self.query_sql count_sql = 'select count(*) from \"'..self.table..'\" '..self.query_sql
end end
total = self:query(count_sql, READ) code, total = self:query(count_sql, READ)
if not total then if code == 0 then
else data['total'] = tonumber(total[1]['count'])
data['total'] = tonumber(total[1]['count(*)'])
data['data'] = self:make_relations(self:query(sql, READ)) data['data'] = self:make_relations(self:query(sql, READ))
end end
--暂时没有理清下面的业务逻辑
if (table.getn(data['data']) + ((page_num - 1)* per_page)) < data['total'] then if (table.getn(data['data']) + ((page_num - 1)* per_page)) < data['total'] then
data['next_page'] = page_num + 1 data['next_page'] = page_num + 1
end end
if tonumber(page_num) ~= 1 then if tonumber(page_num) ~= 1 then
data['prev_page'] = page_num - 1 data['prev_page'] = page_num - 1
end end
return data return data
end end
@ -365,30 +363,29 @@ end
--查询数据表中的数据记录 --查询数据表中的数据记录
function _M:query(sql, type) function _M:query(sql, type)
if not sql then if not sql then
return ngx.log(ngx.ERR,'query() function need sql to query') ngx.log(ngx.ERR,'query() function need sql to query')
return 2, nil
end end
self.query_sql = nil self.query_sql = nil
self.has_order_by = false self.has_order_by = false
if type == READ then if type == READ then
local result, err = database_read:db_query(sql) local code, result = database_read:db_query(sql)
if err ~= nil then if code ~= 0 then
ngx.log(ngx.ERR, "read db error. res: " .. (err or "no reason")) ngx.log(ngx.ERR, "read db error. res: " .. tostring(code).." or no reason")
ngx.exit(500) return code, nil
return
end end
return result return code, result
elseif type == WRITE then elseif type == WRITE then
local result, err = database_write:db_query(sql) local code, result = database_write:db_query(sql)
if err ~= nil then if code ~= 0 then
ngx.log(ngx.ERR, "write db error. res: " .. (err or "no reason")) ngx.log(ngx.ERR, "write db error. res: " .. (code or "no reason"))
ngx.exit(500) return code, nil
return
end end
return result.affected_rows return code, result.affected_rows
else else
ngx.log(ngx.ERR, 'type invalid, need ' .. READ .. ' or '..WRITE) ngx.log(ngx.ERR, 'type invalid, need ' .. READ .. ' or '..WRITE)
ngx.exit(500) ngx.exit(500)
return return 2, nil
end end
end end
@ -397,9 +394,13 @@ function _M:get_hidden()
return self.hidden return self.hidden
end end
function _M:debug()
ngx.log(ngx.INFO, self.table.." ")
end
--初始化数据表中的字段 --初始化数据表中的字段
function _M:new(table, attributes, hidden) function _M:new(table, attributes, hidden)
return setmetatable({ local obj = {
table = table, table = table,
attributes = attributes or {}, attributes = attributes or {},
hidden = hidden or {}, hidden = hidden or {},
@ -410,7 +411,9 @@ function _M:new(table, attributes, hidden)
}, },
relation_sql = nil, relation_sql = nil,
--soft_delete_column = 'deleted_at' --soft_delete_column = 'deleted_at'
}, mt) }
setmetatable(obj, {__index = _M})
return obj
end end
return _M return _M