当Dbh查询在FreeSWITCH中返回零行时,如何在Lua脚本中匹配“ -ERR无回复”?

时间:2019-06-24 21:53:55

标签: sql postgresql lua freeswitch

PostgreSQL表:

mydb=# table phone_numbers;

 pn_id | user_id | phone_number
-------+---------+--------------
     1 |       2 | 5550001111
     4 |       2 | 5552223333

给出下面的Lua脚本,

conn_string =
 "pgsql://hostaddr=1.2.3.4"                 ..
 " dbname=mydb"                             ..
 " user=postgres"                           ..
 " password=postgres"                       ..
 " options='-c client_min_messages=NOTICE'" ..
 " application_name='myapp'"

dbh = freeswitch.Dbh(conn_string)

assert(dbh:connected())
freeswitch.consoleLog("INFO", "lua script: connected to DB")

q =
  "SELECT user_id, phone_number " ..
    "FROM phone_numbers "         ..
    "WHERE phone_number = '5552223333'"

dbh:query(q, function(row)

  freeswitch.consoleLog("INFO", "log from dbh:query callback")

  for column_name, row_val in pairs(row) do
    stream:write(string.format("%5s : %s\n", column_name,  row_val))
  end

end)

dbh:release()

fs_cli中调用会导致

freeswitch@server> lua test.lua
user_id : 2
phone_number : 5552223333

[INFO] switch_cpp.cpp:1443 lua script: connected to DB
[INFO] switch_cpp.cpp:1443 log from dbh:query callback

另一方面,当使用不返回任何行的查询时,例如

q =
  "SELECT user_id, phone_number " ..
    "FROM phone_numbers "         ..
    "WHERE phone_number = '1234567890'"

然后返回“错误”,甚至不调用dbh:query()回调:

freeswitch@server> lua test.lua
-ERR no reply

[INFO] switch_cpp.cpp:1443 lua script: connected to DB

将“错误”用引号引起来,因为它看起来不像是一个错误;至少我尝试过pcall,但没有任何乐趣。

匹配-ERR no reply结果(当查询结果为零行时)非常重要,这样在这种情况下可以挂断电话。


解决方法

仅作记录,我通过使用EXISTSCOALESCE调整SQL查询来找出一种解决方法,因为它们始终提供可以与脚本匹配的返回值,但是我敢肯定有更好的方法。例如:

q = 
  "SELECT COALESCE("        ..
    "SELECT user_id, phone_number "     ..
    "FROM phone_numbers "               ..
    "WHERE phone_number = '1234567890'" ..
    ", '0'" ..
  ")"

dbh:query(q, function(row)   
  if row.coalesce == "0" then
    freeswitch.consoleLog("INFO", "zero results")         
  end
end)    

1 个答案:

答案 0 :(得分:0)

如果查询没有结果,则回调将不会运行。但是,您可以在回调内部设置局部变量,因此您知道回调是否运行(也就是查询中有结果),例如:

q = 
  "SELECT COALESCE("        ..
    "(SELECT phone_number " ..
      "FROM phone_numbers " ..
      "WHERE phone_number = '" .. ani .. "')" ..
    ", '0'" ..
  ")"

local got_results
dbh:query(q, function(row)   
  got_results = true
  -- whatever else you need to do
end)   

if not got_results then
  freeswitch.consoleLog("INFO", "zero results") 
  -- do what you need to with zero results
end