[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Breaking out of a function loop when querying a database that returns multiple rows of data
- From: Sean Conner <sean@...>
- Date: Mon, 21 Sep 2015 19:14:06 -0400
It was thus said that the Great Jonathan Goble once stated:
> On Mon, Sep 21, 2015 at 6:17 PM, Jonathan Hunter
> <jhunter@voxboxcoms.co.uk> wrote:
> > HI Jonathan,
> >
> > Thanks for the reply!
> >
> > Could you just give me an idea of the code, as if I try break it says its
> > outside of the loop, and return doesnt exit the function loop, as I presume
> > my if statements are causing issues,
> >
> > An idea of my code is;
> >
> > assert (dbh:query(todnew_query,function(todresult)
> > local t = os.date("*t");
> > if (tostring(todresult.year) == tostring(t.year) and
> > tostring(todresult.month) == tostring(t.month)) then
> > freeswitch.consoleLog("notice","Year and Month Match, next step is
> > day of month\n")
> > if (tostring(todresult.dayofmonth) == tostring(t.day)) then
> > freeswitch.consoleLog("notice","This entry matches on Day of month
> > too\n")
> > return <<---tried return or break here, is this correct?
> > end
> > if (tostring(t.day) >= startday) and (tostring(t.day) <= endday)
> > then
> > freeswitch.consoleLog("notice", "Today is in the time range\n")
> >
> > end
> > end
> > end))
>
> By "loop", I assumed you meant a "for" loop in Lua. This is not a
> "for" loop, thus "break" won't work. Also, this appears to be calling
> the function separately on every table row produced by the query, so
> "return" won't prevent it from processing others as well.
>
> So you would need to either check the documentation for the database
> wrapper library that you're using for a solution, or failing that,
> figure out a solution in pure SQL, as suggested by Sean Conner between
> your reply and this reply:
Well, actually, he *could* break out of it:
okay,results = pcall(dbh.query,dbh,todnew_query,function(result)
if criteria(result) then
error(result)
end)
The error() is caught by pcall() and passes the "error" (which in this
case, isn't an error but the desired result) back to the caller. If okay is
true, then db.query() ran to completion and didn't find anything, otherwise,
if okay if false, there's a result.
Hmm ... perhaps better would be:
result,data = pcall(...)
would be better:
if result then
use(data)
else
error("the real error")
end
-spc (But I think this approach is ... um ... ugly ... )