如何在Lua脚本中处理FreeSWITCH的Dbh查询返回零行时匹配"-ERR no reply"?

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脚本:连接到数据库")

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

dbh:query(q, function(row)

  freeswitch.consoleLog("INFO", "dbh:query回调中的日志")

  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脚本:连接到数据库
[INFO] switch_cpp.cpp:1443 dbh:query回调中的日志

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

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

那么将返回一个 "error" 并且 dbh:query() 回调甚至不会被调用:

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

[INFO] switch_cpp.cpp:1443 lua脚本:连接到数据库

将 "error" 用引号括起来,因为它似乎不像错误处理一样工作;至少,我尝试了pcall,但没有成功。

匹配 -ERR no reply 结果(当查询结果为零行时)将是重要的,这样在这种情况下可以挂断呼叫。


解决方法

仅是为了记录,我通过调整SQL查询来找到了解决方法,使用 EXISTSCOALESCE ,因为它们始终提供可以从脚本中匹配的返回值,但我相信还有更好的方法。例如:

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", "零结果")
  end
end)
点赞
用户3830401
用户3830401

如果查询没有结果,回调函数将不会运行。但是,您可以在回调函数中设置一个本地变量,以便知道回调函数是否运行(即查询是否有结果)。例如:

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
  -- 其他必要的操作
end)

if not got_results then
  freeswitch.consoleLog("INFO", "零结果")
  -- 处理零结果的操作
end
2019-06-25 01:41:22