Skip to content

Commit

Permalink
More model<->db functions
Browse files Browse the repository at this point in the history
Now find is find_by_id and we have a new find that receives a where_string.
And find_all now can receive a where_string too.
  • Loading branch information
Etiene committed Jan 10, 2014
1 parent 23694c5 commit b015542
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 11 deletions.
18 changes: 11 additions & 7 deletions controllers/site.lua
Original file line number Diff line number Diff line change
Expand Up @@ -9,40 +9,44 @@ function site.index(page)


--Testing models
local User = sailor.model("user")
--[[local User = sailor.model("user")
local u = User:new()
u.name = "jorge"
u.name = "francisco"
u.password = "blah"
if(u:save()) then
page:write("saved! "..u.id.."<br/>")
end
local u2 = User:find("name = 'francisco'")
if u2 then
page:write(u2.id.." - "..u2.name.."<br/>")
end
local users = User:find_all()
for _, user in pairs(users) do
page:write(user.id.." - "..user.name.."<br/>")
end

u.name = "roberto"
if(u:save()) then
page:write("saved! "..u.id.."<br/>")
end
local users = User:find_all()
local users = User:find_all()
for _, user in pairs(users) do
page:write(user.id.." - "..user.name.."<br/>")
end
--[[page:write("Finding user with id 1:<br/>")
local some_user = User:find(1)
page:write("Finding user with id 1:<br/>")
local some_user = User:find_by_id(1)
page:write(some_user.id.." - "..some_user.name.."<br/>")
page:write("Finding user with id 47:<br/>")
local some_user = User:find(47)
local some_user = User:find_by_id(47)
page:write(some_user.id.." - "..some_user.name.."<br/>")
]]

Expand Down
22 changes: 18 additions & 4 deletions src/model.lua
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,7 @@ function model:update()
return (db.query(query) ~= 0)
end

function model:find(id)
local cur = db.query("select * from "..self.db.table.." where "..self.db.key.."='"..id.."';")
function model:fetch_object(cur)
local row = cur:fetch ({}, "a")
cur:close()
if row then
Expand All @@ -96,9 +95,24 @@ function model:find(id)
end
end

function model:find_all()
function model:find_by_id(id)
local cur = db.query("select * from "..self.db.table.." where "..self.db.key.."='"..id.."';")
return self:fetch_object(cur)
end

function model:find(where_string)
local cur = db.query("select * from "..self.db.table.." where "..where_string..";")
return self:fetch_object(cur)
end

function model:find_all(where_string)
local key = self.db.key
local cur = db.query("select * from "..self.db.table..";")
if where_string then
where_string = " where "..where_string
else
where_string = ''
end
local cur = db.query("select * from "..self.db.table..where_string..";")
local res = {}
local row = cur:fetch ({}, "a")
while row do
Expand Down

0 comments on commit b015542

Please sign in to comment.