The PostgreSQL table:
mydb=# table phone_numbers;
pn_id | user_id | phone_number
-------+---------+--------------
1 | 2 | 5550001111
4 | 2 | 5552223333
Given the Lua script below,
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()
calling it in fs_cli results in
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
On the other hand, when using a query that wouldn't return any rows, such as
q =
"SELECT user_id, phone_number " ..
"FROM phone_numbers " ..
"WHERE phone_number = '1234567890'"
then an "error" is returned and the dbh:query() callback is not even called:
freeswitch@server> lua test.lua
-ERR no reply
[INFO] switch_cpp.cpp:1443 lua script: connected to DB
Putting "error" in quotes, because it doesn't seem to behave as one; at least, I tried pcall but no joy.
Matching the -ERR no reply result (when the query results in zero rows) would be important so that the call could be hung up in that case.
Workaround
Just for the record, I figured out a workaround by tweaking the SQL query using EXISTS or COALESCE as they always provide a return value that can be matched from the script, but I'm sure there's a better way. For example:
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)