Compare commits

..

No commits in common. "df3a0f6adfdb269974b0574f351ff5aede442e28" and "839fbf4d78c5f3c1a13276e13cb6278ff082b688" have entirely different histories.

11 changed files with 200 additions and 860 deletions

View File

@ -12,15 +12,6 @@ local validator = require("util.validator")
--获取所有用户信息
function _M.get_alluser()
--获取页码和请求的数据量
local page = 0
local pagesize = 0
local payloads = ngx.req.get_uri_args()
for k,v in pairs(payloads) do
if k == "page" then page = v end
if k == "pagesize" then pagesize = v end
end
--ngx.say("page:", page, " pagesize:", pagesize)
local code,ret = dao.getAllUser()
local result = resp:json(code, ret)
resp:send(result)
@ -61,7 +52,7 @@ end
--根据用户id删除用户信息
function _M.delete_user(m)
local id = m.id
local code, ret = dao.deleteUser(id)
local code, ret = dao.delete_user(id)
local result = resp:json(code, ret)
resp:send(result)
end
@ -79,7 +70,7 @@ function _M.update_user(m)
resp:send(result)
return
end
local code, ret = dao.updateUser(id, body_data)
local code, ret = dao.update_user(id, body_data)
local result = resp:json(code, ret)
resp:send(result)
end

View File

@ -24,6 +24,6 @@ return {
PORT = 5432, -- postgres port
USERNAME = "postgres",
PASSWORD = "1qaz2wsx", -- postgres password
DATABASE = "postgres",
DATABASE = "postgres"
}
}

View File

@ -13,25 +13,6 @@ return {
port = env.POSTGRES.PORT,
user = env.POSTGRES.USERNAME,
password = env.POSTGRES.PASSWORD,
database = env.POSTGRES.DATABASE,
write = { -- postgresql write database
host = env.POSTGRES.HOST,
port = env.POSTGRES.PORT,
user = env.POSTGRES.USERNAME,
password = env.POSTGRES.PASSWORD,
database = env.POSTGRES.DATABASE
},
read = { -- postgresql read database
host = env.POSTGRES.HOST,
port = env.POSTGRES.PORT,
user = env.POSTGRES.USERNAME,
password = env.POSTGRES.PASSWORD,
database = env.POSTGRES.DATABASE
},
charset = 'utf8',
pool_timeout = 1000, -- postgresql pool timeout
pool_size = 100, -- postgresql pool size
timeout = 1000, -- postgresql timeout
database = env.POSTGRES.DATABASE
},
}

View File

@ -1,12 +0,0 @@
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by admin.
--- DateTime: 2025/10/25 16:36
--- 数据表模型文件
--引用使用的库文件
local Model = require("util.model")
--创建一个数据表相关的模型
local Account = Model:new('tbl_account')
return Account

View File

@ -1,12 +0,0 @@
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by admin.
--- DateTime: 2025/10/25 16:36
--- 数据表模型文件
--引用使用的库文件
local Model = require("util.model")
--创建一个数据表相关的模型
local User = Model:new('tbl_user')
return User

View File

@ -3,20 +3,72 @@
--- Created by .
--- DateTime: 2025/9/25 08:19
--- 业务逻辑 对用户数据表进行数据表业务处理
local pgmoon = require('pgmoon')
local dbconf = require("config.database")
local status = require("config.status")
local validator = require("util.validator")
local helpers = require("util.helpers")
local account = require("model.account")
local _M = {}
-- 查询数据表中的所有账号信息
function _M.getAllAccount()
return account:all()
--获取一个数据库操作连接
local function get_con(cfg)
local code = 0
-- 创建一个新的连接
local conn = pgmoon.new(cfg);
---- 连接到数据库
local ok, err = conn:connect()
if not ok then
print("Connection failed: " .. err)
code = 0x000002
end
--ngx.say("Connection success")
return code,conn
end
--根据账号id获取账号信息
--数据库执行sql语句
local function execSQL(sql)
local res = nil
if sql == '' or sql == nil then
return 0x000003,res
end
--获取数据库连接
local code,conn = get_con(dbconf.postgres)
if code ~= 0 then
return 0x000003,res
end
--执行数据库操作
res = conn:query(sql)
if not res then
print("query sql failed: "..sql)
return 0x000003,res
end
--关闭数据库
conn:disconnect()
return code,res
end
--通过查询条件判断数据库中的数据记录
local function checkAccountExist(where)
--组装sql语句
local sql = string.format("select count(*) as count from \"tbl_account\" %s", where)
--ngx.say("check sql: "..sql)
--获取数据库连接
return execSQL(sql)
end
-- 查询数据表中的所有账号信息
function _M.getAllAccount()
--组装sql语句
local sql = "select * from \"tbl_account\""
return execSQL(sql)
end
--根据用户id获取账号信息
function _M.getAccount(id)
return account.find(id)
--组装sql语句
local sql = "select * from \"tbl_account\" where id='"..id.."'"
return execSQL(sql)
end
--增加账号信息到数据表
@ -24,65 +76,81 @@ function _M.addAccount(jsonData)
--验证数据的正确性,错误时返回
local success, result = validator.checkJson(jsonData)
if success == false then
return 0x000001, result
return 0x000001,result
end
--解析json中的键和数据值
local keys = ""
local values = ""
local name = ""
for key, value in pairs(result) do
keys = keys..key..","
values = values..((type(value) == "string") and "'"..value.."'" or value)..","
if key == "name" then name = value end
end
--根据账号进行验证是否存在
local code, res = account:where("name", "=", name):get()
if code ~= 0 then
return 0x000001, res
--根据用户进行验证用户是否存在
local where = string.format("where name='%s'", name)
local ok, res = checkAccountExist(where)
if ok ~= 0 then
return 0x000001,res
end
local num = 0
for _, row in ipairs(res) do
for key, value in pairs(row) do
num = num + 1
num = value
end
end
--账号存在时返回账号已经存在
if num <= 0 then
return 0x01000C, nil
print("exec result:", num)
if num > 0 then
return 0x010000,nil
end
--自己增加对应的uuid数据值
local newKeys = "id"
local newValues = "'"..helpers.getUuid().."'"
-- 创建一个账号
return account:create(jsonData)
local newKeys = keys.."id"
local newValues = values.."'"..helpers.getUuid().."'"
--组装sql语句
local sql = string.format("insert into \"tbl_account\"(%s)values(%s)", newKeys, newValues)
return execSQL(sql)
end
--增加账号信息到数据表
function _M.deleteAccount(id)
return account:delete(id)
--组装sql语句
local sql = "delete from \"tbl_account\" where id='"..id.."'"
return execSQL(sql)
end
--更新账号信息到数据表
function _M.updateAccount(id, jsonData)
--根据账号id进行验证账号是否存在
local code, res = account:find(id)
if code ~= 0 then
return 0x000001, res
--根据用户id进行验证用户是否存在
local where = string.format("where id='%s'", id)
local ok, res = checkAccountExist(where)
if ok ~= 0 then
return 0x000001,res
end
local num = 0
for _, row in ipairs(res) do
for key, value in pairs(row) do
num = num + 1
num = value
end
end
--账号不存在返回错误
print("exec result:", num)
if num <= 0 then
return 0x01000C, nil
return 0x01000C,nil
end
--验证数据的正确性,错误时返回
local success, result = validator.checkJson(jsonData)
if success == false then
return 0x000001, result
return 0x000001,result
end
--对数据内容进行更新
return account:where('id', '=', id):update(jsonData)
--解析json中的键和数据值
local tmp = ""
for key, value in pairs(result) do
local val = (type(value) == "string") and "'"..value.."'" or value
tmp = string.format("%s=%s,", key, val)
end
local vals = tmp:sub(1, #tmp - 1)
--组装sql语句
local sql = string.format("update \"tbl_account\" set %s where id='%s'", vals, id)
return execSQL(sql)
end
return _M

View File

@ -3,20 +3,72 @@
--- Created by .
--- DateTime: 2025/9/25 08:19
--- 业务逻辑 对用户数据表进行数据表业务处理
local pgmoon = require('pgmoon')
local dbconf = require("config.database")
local status = require("config.status")
local validator = require("util.validator")
local helpers = require("util.helpers")
local user = require("model.user")
local _M = {}
--获取一个数据库操作连接
local function get_con(cfg)
local code = 0
-- 创建一个新的连接
local conn = pgmoon.new(cfg);
---- 连接到数据库
local ok, err = conn:connect()
if not ok then
print("Connection failed: " .. err)
code = 0x000002
end
--ngx.say("Connection success")
return code,conn
end
--数据库执行sql语句
local function execSQL(sql)
local res = nil
if sql == '' or sql == nil then
return 0x000003,res
end
--获取数据库连接
local code,conn = get_con(dbconf.postgres)
if code ~= 0 then
return 0x000003,res
end
--执行数据库操作
res = conn:query(sql)
if not res then
print("query sql failed: "..sql)
return 0x000003,res
end
--关闭数据库
conn:disconnect()
return code,res
end
--通过查询条件判断数据库中的数据记录
local function checkUserExist(where)
--组装sql语句
local sql = string.format("select count(*) as count from \"tbl_user\" %s", where)
print("check sql: "..sql)
--获取数据库连接
return execSQL(sql)
end
-- 查询数据表中的所有用户信息
function _M.getAllUser()
return user:all()
--组装sql语句
local sql = "select * from \"tbl_user\""
return execSQL(sql)
end
--根据用户id获取用户信息
function _M.getUser(id)
return user:find(id)
--组装sql语句
local sql = "select * from \"tbl_user\" where id='"..id.."'"
return execSQL(sql)
end
--增加用户信息到数据表
@ -27,56 +79,62 @@ function _M.addUser(jsonData)
return 0x000001,result
end
--解析json中的键和数据值
local name, phone, email
local keys = ""
local values = ""
local username, phone, email
for key, value in pairs(result) do
if key == "username" then name = value end
keys = keys..key..","
values = values..((type(value) == "string") and "'"..value.."'" or value)..","
if key == "username" then username = value end
if key == "phone" then phone = value end
if key == "email" then email = value end
end
--根据用户、手机号、邮箱进行验证用户是否存在
local code, res = user:where("name", "=", name).where("phone", "=", phone).where("email", "=", phone):get()
if code ~= 0 then
local where = string.format("where username='%s' or phone='%s' or email='%s'", username, phone, email)
local ok, res = checkUserExist(where)
if ok ~= 0 then
return 0x000001,res
end
local num = 0
for _, row in ipairs(res) do
for key, value in pairs(row) do
num = num + 1
num = value
end
end
--用户存在时返回用户已经存在
if num <= 0 then
return 0x01000C,nil
print("exec result:", num)
if num > 0 then
return 0x010000,nil
end
--产生uuid数据值增加到json中
local newKeys = "id"
local newValues = "'"..helpers.getUuid().."'"
-- 创建一个用户
return user:create(jsonData)
--自己增加对应的uuid数据值
local newKeys = keys.."id"
local newValues = values.."'"..helpers.getUuid().."'"
--组装sql语句
local sql = string.format("insert into \"tbl_user\"(%s)values(%s)", newKeys, newValues)
return execSQL(sql)
end
--增加用户信息到数据表
function _M.deleteUser(id)
return user:delete(id)
--组装sql语句
local sql = "delete from \"tbl_user\" where id='"..id.."'"
return execSQL(sql)
end
--更新用户信息到数据表
function _M.updateUser(id, jsonData)
--根据用户id进行验证用户是否存在
local code, res = user:find(id)
if code ~= 0 then
local where = string.format("where id='%s'", id)
local ok, res = checkUserExist(where)
if ok ~= 0 then
return 0x000001,res
end
local num = 0
for _, row in ipairs(res) do
for key, value in pairs(row) do
num = num + 1
num = value
end
end
--用户不存在返回错误
print("exec result:", num)
if num <= 0 then
return 0x01000C,nil
end
@ -85,8 +143,16 @@ function _M.updateUser(id, jsonData)
if success == false then
return 0x000001,result
end
--对数据内容进行更新
return user:where('id', '=', id):update(jsonData)
--解析json中的键和数据值
local tmp = ""
for key, value in pairs(result) do
local val = (type(value) == "string") and "'"..value.."'" or value
tmp = string.format("%s=%s,", key, val)
end
local vals = tmp:sub(1, #tmp - 1)
--组装sql语句
local sql = string.format("update \"tbl_user\" set %s where id='%s'", vals, id)
return execSQL(sql)
end
return _M

View File

@ -13,94 +13,11 @@
--max =a and b or c--a?b:c
local User = require("model.user")
--获取数据表中的记录数
local code, res = User:count()
--ngx.say(res)
--查询表中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
--ngx.say("----begin where and query---")
-- 返回 users 表中 username 字段的值是 `cgreen` 的,`password` 字段的值是 `xxxxxx` 的多条数据,注意此处返回是 table 数组,`first()` 方法返回的是单条数据
code, res = User:where('name','=','zhangsan'):where('password','=','111111'):get()
--for _, row in ipairs(res) do
-- for key, value in pairs(row) do
-- ngx.say(key .. ":" .. tostring(value))
-- end
--end
--ngx.say("----begin where or query---")
-- 返回 `name` 为 `xxx` 或者 `yyy` 的所有用户 table 数组
code, res = User:where('name','=','zhangsan'):orwhere('name','=','admin'):get()
--for _, row in ipairs(res) do
-- for key, value in pairs(row) do
-- ngx.say(key .. ":" .. tostring(value))
-- end
--end
--orderby(column, option)方法第一个参数传入排序的列名第二个参数默认为ASC 也可以传入 ASC 正序 或 DESC 倒序(不区分大小写)
code, res = User:orderby('created_time'):get()
--for _, row in ipairs(res) do
-- for key, value in pairs(row) do
-- ngx.say(key .. ":" .. tostring(value))
-- end
--end
-- 创建一个用户
code, res = User:create({
id='3',
password='22222',
name='lisi',
email='lisi@gmail.com',
})
-- 更新 id = 1 的 user 的 name 为 test, avatar 为 NULL
code, res = User:where('id', '=', '3'):update({
phone='666666',
email='zhangsan@qq.com'
})
--输出更新后影响的行总数
ngx.say("update affected_rows: ", res.affected_rows)
-- 删除 id = 1 的用户
code, res = User:where('id','=','3'):delete()
ngx.say("delete affected_rows: ", res.affected_rows)
--分页 获取数据表中的记录
local data = nil
code, data = User:paginate(1)
local count = data.total
ngx.say("data total:", count)
for _, row in ipairs(data.data) do
ngx.say("begin show data:")
for key, value in pairs(row) do
ngx.say(key .. ":" .. tostring(value))
end
end
--获取请求参数的键值和数据值
--local cjson = require("cjson")
--local header = ngx.req.get_headers()
--for k,v in pairs(header) do
-- ngx.say("[header] name:", k, "value:", v)
--end
--
--local payloads = ngx.req.get_uri_args()
--for k,v in pairs(payloads) do
-- ngx.say("[params] name:", k, " value:", v)
--end
local cjson = require("cjson")
local header = ngx.req.get_header()
local payload = ngx.req.get_payload()
ngx.say("payload:", payload)
--去掉组装最后一位逗号(,)
--local newKeys = keys:sub(1, #keys -1)
--local newValues = values:sub(1, #values -1)

View File

@ -1,96 +0,0 @@
local pgmoon = require('pgmoon')
local ngx = ngx
local _M = {}
local WRITE = 'WRITE'
local READ = 'READ'
local mt = { __index = _M }
--[[
Get db connection from connection pool
@return bool, db_context, err
--]]
function _M:get_connection()
local code = 0
if ngx.ctx[self.db_type] then
-- if write before read, make sure write read connection the same
if ngx.ctx[WRITE] then
return code, ngx.ctx[WRITE]
end
return code, ngx.ctx[self.db_type]
end
-- 创建一个新的连接
local conn = pgmoon.new({
host = self.host, -- postgres host
port = self.port, -- postgres port
user = self.user,
password = self.password, -- postgres password
database = self.database
});
--conn.set_timeout(self.timeout or 1000)
---- 连接到数据库
local ok, err = conn:connect()
if not ok then
print("Connection failed: " .. err)
code = 0x000002
end
ngx.log(ngx.INFO, 'Connection success')
--ngx.say("Connection success")
ngx.ctx[self.db_type] = conn
return code,conn
end
--[[
set_keepalive代替close() ,nginx工作进程
@return void
--]]
function _M.close(self)
if ngx.ctx[READ] then
ngx.ctx[READ]:set_keepalive(self.db_pool_timeout, self.db_pool_size)
ngx.ctx[READ] = nil
end
if ngx.ctx[WRITE] then
ngx.ctx[WRITE]:set_keepalive(self.db_pool_timeout, self.db_pool_size)
ngx.ctx[WRITE] = nil
end
end
--[[
@param sql
@return bool, data, err
--]]
function _M.db_query(self, sql)
local code, conn = self:get_connection()
if code ~= 0 then
return code,nil
end
ngx.log(ngx.INFO, 'begin db query :' .. sql)
-- 执行查询
local res, err = conn:query(sql)
if not res then
ngx.log(ngx.ERR, 'Query failed:' .. sql)
return 2,nil
end
return 0, res
end
function _M.new(self, opts)
return setmetatable({
host = opts.host or '127.0.0.1',
port = opts.port or 5432,
user = opts.user or 'postgres',
password = opts.password or '',
database = opts.database or 'postgres',
--charset = opts.charset or 'utf8mb4',
--timeout = opts.timeout or 1000,
--max_packet_size = 1024 * 1024,
db_pool_timeout = opts.pool_timeout or 1000,
db_pool_size = opts.pool_size or 1000,
db_type = opts.db_type,
}, mt)
end
return _M

View File

@ -4,11 +4,10 @@
--- DateTime: 2025/10/24 11:36
---
local snowflake = require("util.snowflake")
local cjson = require("cjson")
local _M = {}
local function getUuid()
function _M:getUuid()
local workerId = 0 -- 假设当前机器的ID是1范围在[0, 31]之间
local datacenterId = 0 -- 数据中心ID范围在[0, 31]之间
local snow = snowflake.new(workerId, datacenterId)
@ -17,154 +16,4 @@ local function getUuid()
return snow.int64_to_string(id)
end
-- here you need use . not :
local function table_reverse(tbl)
for i=1, math.floor(#tbl / 2) do
tbl[i], tbl[#tbl - i + 1] = tbl[#tbl - i + 1], tbl[i]
end
return tbl
end
-- remove item in table
local function table_remove(tab, rm)
local result = tab
for k, v in pairs(rm) do
for a_k, a_v in pairs(result) do
-- array
if type(a_k) == 'number' then
-- object
if type(a_v) == 'table' then
result[a_k][v] = nil
elseif v == a_v then
table.remove(result, a_k)
end
else
-- hash array
if v == a_k then
result[a_k] = nil
end
end
end
end
return result
end
-- unique a array
local function unique(arr)
local hash = {}
local res = {}
for _,v in ipairs(arr) do
if not hash[v] then
hash[v] = true
table.insert(res, v)
end
end
return res
end
-- make up a string from array
local function implode(arr, symbol)
local implode_str = ''
symbol = symbol or ','
for key, value in pairs(arr) do
implode_str = implode_str .. value .. symbol
end
return string.sub(implode_str, 1, #implode_str - 1)
end
-- sort a hashTable by key
local function sort_by_key(tab)
local a = {}
for n in pairs(tab) do
table.insert(a, n)
end
table.sort(a)
local i = 0 -- iterator variable
local iter = function()
-- iterator function
i = i + 1
if a[i] then
return a[i], tab[a[i]]
else
return nil
end
end
return iter
end
local function set_cookie(key, value, expires)
local config = require("config.app")
local cookie, err = require("util.cookie"):new()
if not cookie then
ngx.log(ngx.ERR, err)
return false, err
end
local cookie_payload = {
key = key,
value = value,
path = '/',
domain = config.app_domain,
httponly = true,
}
if expires ~= nil then
cookie_payload.expires = ngx.cookie_time(expires)
end
local ok, err = cookie:set(cookie_payload)
if not ok then
ngx.log(ngx.ERR, err)
return false, err
end
return true
end
local function get_cookie(key)
local cookie, err = require("util.cookie"):new()
if not cookie then
ngx.log(ngx.ERR, err)
return false
end
return cookie:get(key)
end
local function get_local_time()
local config = require("config.config")
local time_zone = ngx.re.match(config.time_zone, "[0-9]+")
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
ngx.log(ngx.ERR, err)
return false, err
end
-- ngx.time() return UTC+0 timestamp
-- time_zone * 60(sec) * 60(min) + UTC+0 time = current time
return time_zone[0] * 3600 + ngx.time()
end
local function trim(str, symbol)
symbol = symbol or '%s' -- %s default match space \t \n etc..
return (string.gsub(string.gsub(str, '^' .. symbol .. '*', ""), symbol .. '*$', ''))
end
-- data not in order
local function log(...)
local args
if #{...}>1 then
args = {...}
else
args = ...
end
ngx.log(ngx.WARN, cjson.encode(args))
end
_M.getUuid = getUuid
_M.log = log
_M.trim = trim
_M.get_cookie = get_cookie
_M.set_cookie = set_cookie
_M.get_local_time = get_local_time
_M.sort_by_key = sort_by_key
_M.implode = implode
_M.unique = unique
_M.table_reverse = table_reverse
_M.table_remove = table_remove
return _M

View File

@ -1,412 +0,0 @@
local Database = require('util.database')
local dbconf = require("config.database")
local helpers = require('util.helpers')
local implode = helpers.implode
local unique = helpers.unique
local table_remove = helpers.table_remove
local _M = {}
local WRITE = 'WRITE'
local READ = 'READ'
local database_write = Database:new({
host = dbconf.postgres.write.host,
port = dbconf.postgres.write.port,
user = dbconf.postgres.write.user,
password = dbconf.postgres.write.password,
database = dbconf.postgres.write.database,
--charset = dbconf.postgres.charset,
--timeout = dbconf.postgres.timeout,
db_pool_timeout = dbconf.postgres.pool_timeout,
db_pool_size = dbconf.postgres.pool_size,
db_type = WRITE
})
local database_read = Database:new({
host = dbconf.postgres.read.host,
port = dbconf.postgres.read.port,
user = dbconf.postgres.read.user,
password = dbconf.postgres.read.password,
database = dbconf.postgres.read.database,
--charset = dbconf.postgres.charset,
--timeout = dbconf.postgres.timeout,
db_pool_timeout = dbconf.postgres.pool_timeout,
db_pool_size = dbconf.postgres.pool_size,
db_type = READ
})
local function transform_value(value)
if value == ngx.null then
value = ''
end
value = value or ''
if string.lower(value) == 'null' then
return 'NULL'
end
return ngx.quote_sql_str(value)
end
-- return whole relations keys
--获取整个关系的键值
function _M:get_relation_local_index(parents)
local ids = {}
for key,parent in pairs(parents) do
table.insert( ids, parent[self.relation.local_key] )
end
return ids
end
-- return whole relation models
function _M:retrieve_relations(ids)
-- if table is empty
if next(ids) == nil then
return {}
end
local ids_str = implode(unique(ids))
self.relation_sql = 'select * from \"'..self.relation.model.table..'\" where ' .. self.relation.foreign_key .. ' in (' .. ids_str .. ')'
return table_remove(self:query(self.relation_sql, READ), self.relation.model:get_hidden())
end
-- return current parent node
function _M:merge_one_relation(parent, relations)
for _, item in pairs(relations) do
if (parent[self.relation.local_key] == item[self.relation.foreign_key]) then
parent[self.relation.key_name] = item
end
end
return parent
end
function _M:merge_many_relations(parent, relations)
for index, item in pairs(relations) do
if (parent[self.relation.local_key] == item[self.relation.foreign_key]) then
if not parent[self.relation.key_name] then
parent[self.relation.key_name] = {}
end
table.insert(parent[self.relation.key_name], item)
end
end
return parent
end
function _M:make_relations(parents)
if self.relation.mode ~= 0 then
local relations = self:retrieve_relations(self:get_relation_local_index(parents))
for key, parent in pairs(parents) do
if self.relation.mode == 1 then
-- belongs to
if table.getn(relations) > 0 then
parents[key] = self:merge_one_relation(parent, relations)
else
parents[key][self.relation.key_name] = nil
end
elseif self.relation.mode == 2 then
-- has many
parents[key] = self:merge_many_relations(parent, relations)
end
end
end
return parents
end
-- function _M:merge_hidden()
-- if #self.attributes == 0 then
-- return '*'
-- else
-- local result = table_remove(self.attributes, self.hidden)
-- return table.concat(result, ", ")
-- end
-- end
function _M:find(id,column)
if self.query_sql ~= nil then
ngx.log(ngx.ERR, 'cannot use find() with other query sql')
return 1, nil
end
column = column or 'id'
id = transform_value(id)
ngx.log(ngx.INFO, 'table name :' .. self.table)
local sql = 'select * from \"'..self.table..'\" where '..column..'='..id..' limit 1'
ngx.log(ngx.INFO, 'query sql:', sql)
local code, res = self:query(sql, READ)
if table.getn(res) > 0 then
ngx.log(ngx.INFO, 'query record count:', table.getn(res))
res = self:make_relations(res)
return code, res
end
return code, nil
end
function _M:all()
if self.query_sql ~= nil then
ngx.log(ngx.ERR, 'cannot use all() with other query sql ', self.query_sql)
return 2, nil
end
local code, res = self:query('select * from \"'..self.table..'\"', READ)
return code, self:make_relations(res)
end
--组装sql语句条件为and相关的字段
function _M:where(column,operator,value)
value = transform_value(value)
if not self.query_sql then
self.query_sql = 'where '..column.. ' ' .. operator .. ' ' .. value
else
self.query_sql = self.query_sql..' and '..column..' '..operator..' '..value
end
return self
end
--组装sql语句条件为or相关的字段
function _M:orwhere(column,operator,value)
value = transform_value(value)
if not self.query_sql then
return ngx.log(ngx.ERR,'orwhere function need a query_sql prefix')
else
self.query_sql = self.query_sql..' or '..column..operator..value
end
return self
end
function _M:orderby(column,operator)
local operator = operator or 'asc'
if not self.query_sql then
self.query_sql = 'order by '.. self.table .. '.' .. column .. ' ' ..operator
else
if self.has_order_by then
self.query_sql = self.query_sql .. ',' .. column.. ' ' ..operator
else
self.query_sql = self.query_sql .. ' order by ' .. column.. ' ' ..operator
end
end
self.has_order_by = true
return self
end
--获取数据表中记录的数量
function _M:count()
local sql = ""
if self.query_sql ~= nil then
sql = 'select count(*) from \"'..self.table..'\" '..self.query_sql
else
sql = 'select count(*) from \"'..self.table.."\""
end
local code, res = self:query(sql, READ)
if table.getn(res) > 0 then
return code, tonumber(res[1]['count'])
end
return code, nil
end
-- params: (option)int num
-- return: table
function _M:get(num)
num = num or nil
local limit_sql = ''
if num ~= nil then
limit_sql = 'limit ' .. num
end
if not self.query_sql then
ngx.log(ngx.ERR,'do not have query sql str')
return 2,nil
end
local sql = 'select * from \"'..self.table..'\" '..self.query_sql .. ' ' .. limit_sql
local code,res = self:query(sql, READ)
if self.relation.local_key ~= nil then
return code, self:make_relations(res)
end
return code, res
end
--根据数据模型中的
function _M:paginate(page_num, page_size)
page_num = page_num or 1
page_size = page_size or 10
local sql, count_sql, total, code, res
local data={
data = {},
total = 0
}
if not self.query_sql then
sql = 'select * from \"'..self.table..'\" limit '..page_size..' offset '..(page_num - 1) * page_size
count_sql = 'select count(*) from \"'..self.table..'\"'
else
sql = 'select * from \"'..self.table .. '\" '..self.query_sql .. ' limit '..page_size..' offset '..(page_num - 1) * page_size
count_sql = 'select count(*) from \"'..self.table..'\" '..self.query_sql
end
code, total = self:query(count_sql, READ)
if code == 0 then
data['total'] = tonumber(total[1]['count'])
end
code, res = self:query(sql, READ)
if code == 0 then
data['data'] = self:make_relations(res)
end
return code, data
end
--返回数据表中的第一条数据记录
function _M:first()
if not self.query_sql then
ngx.log(ngx.ERR,'do not have query sql str')
return 2,nil
end
local sql = 'select * from \"'..self.table..'\" '..self.query_sql..' limit 1'
local code, res = self:query(sql, READ)
if next(res) ~= nil then
res = self:make_relations(res)
return code, res[1]
end
return code, nil
end
--插入数据内容到数据表中
function _M:create(data)
local columns,values
for column,value in pairs(data) do
value = transform_value(value)
if not columns then
columns = column
values = value
else
columns = columns..','..column
values = values..','..value
end
end
return self:query('insert into \"'..self.table..'\"('..columns..') values('..values..')', WRITE)
end
function _M:with(relation)
self.relation.key_name = relation
if self[relation] == nil then
ngx.log(ngx.ERR, self.table .. ' dont have ' .. relation .. ' function')
end
return self[relation]()
end
-- 使用数组来存储关系模型
function _M:has_many(model, foreign_key, local_key)
self.relation.model = model
self.relation.local_key = local_key
self.relation.foreign_key = foreign_key
self.relation.mode = 2
return self
end
function _M:belongs_to(model, foreign_key, local_key)
self.relation.model = model
self.relation.local_key = local_key
self.relation.foreign_key = foreign_key
self.relation.mode = 1
return self
end
--根据id删除数据库中的数据记录
function _M:delete(id)
id = id or nil
if not id then
-- 拼接需要delete的字段
if self.query_sql then
--postgres 数据库使用delete语句时不支持limit
--local sql = 'delete from \"'..self.table..'\" '..self.query_sql..' limit 1'
local sql = 'delete from \"'..self.table..'\" '..self.query_sql
return self:query(sql, WRITE)
end
ngx.log(ngx.ERR,'delete function need prefix sql')
return 2, nil
end
--return self:query('delete from '..self.table..' where id=' .. id .. ' limit 1', WRITE)
return self:query('delete from \"'..self.table..'\" where id='.. id, WRITE)
end
--软删除数据,不从数据表中删除记录,只将定义表中的字段值进行处理
--function _M:soft_delete()
-- if self.query_sql then
-- local sql = 'update '..self.table..' set '..self.soft_delete_column..' = now() '.. self.query_sql ..' limit 1'
-- return self:query(sql, WRITE)
-- end
-- ngx.log(ngx.ERR,'soft_delete function cannot called without restriction')
-- ngx.exit(500)
-- return false
--end
--更新数据表中的数据记录
function _M:update(data)
-- 拼接需要update的字段
local str = nil
for column,value in pairs(data) do
local clean_value = transform_value(value)
if not str then
str = column..'='..clean_value
else
str = str..','..column..'='..clean_value
end
end
-- 判断是模型自身执行update还是数据库where限定执行
if self.query_sql then
--postgres 数据库使用update语句时不支持limit
--local sql = 'update \"'..self.table..'\" set '..str..' '..self.query_sql..' limit 1'
local sql = 'update \"'..self.table..'\" set '..str..' '..self.query_sql
return self:query(sql, WRITE)
end
ngx.log(ngx.ERR,'update function cannot called without restriction')
return 2, nil
end
--查询数据表中的数据记录
function _M:query(sql, type)
if not sql then
ngx.log(ngx.ERR,'query() function need sql to query')
return 2, nil
end
self.query_sql = nil
self.has_order_by = false
if type == READ then
local code, result = database_read:db_query(sql)
if code ~= 0 then
ngx.log(ngx.ERR, "read db error. res: " .. tostring(code).." or no reason")
return code, nil
end
return code, result
elseif type == WRITE then
local code, result = database_write:db_query(sql)
if code ~= 0 then
ngx.log(ngx.ERR, "write db error. res: " .. (code or "no reason"))
return code, nil
end
return code, result
end
ngx.log(ngx.ERR, 'type invalid, need ' .. READ .. ' or '..WRITE)
return 2, nil
end
--获取需要隐藏的列
function _M:get_hidden()
return self.hidden
end
function _M:debug()
ngx.log(ngx.INFO, self.table.." ")
end
--初始化数据表中的字段
function _M:new(table, attributes, hidden)
local obj = {
table = table,
attributes = attributes or {},
hidden = hidden or {},
query_sql = nil,
has_order_by = false,
relation = {
mode = 0
},
relation_sql = nil,
--soft_delete_column = 'deleted_at'
}
setmetatable(obj, {__index = _M})
return obj
end
return _M