Lua and mysql-proxy: how to send a query to an email

March 11th, 2011 by Leandro Morgado

I recently got an inquiry on how to receive an email every time a query was executed via the MySQL proxy. This is very simple and you can achieve it by simply piping the query to the *nix mail command. Here is the sample code (in a file caled send_mail.lua):

1
2
3
4
5
6
7
function read_query(packet)
  if string.byte(packet) == proxy.COM_QUERY then
    print("Hello world! Seen the query: " .. string.sub(packet, 2))
    print("Sending query to email:")
    os.execute("echo " .. string.sub(packet, 2) .. "| mail -s'Lua test' your.email.here@example.com ")
  end
end

To execute this, install proxy as per the instructions in the manual. Then simply run the proxy and point it at your script:

shell> bin/mysql-proxy --proxy-lua-script=send_email.lua &

Finally, connect to the proxy and issue a query:

shell> mysql -h127.0.0.1 --port=4040
...
mysql> SELECT "Test 1";
Hello world! Seen the query: SELECT "Test 1"
Sending query to email:
+--------+
| Test 1 |
+--------+
| Test 1 |
+--------+
1 row in set (0.00 sec)

You’ll shorty receive email with the query above. Happy Lua scripting.

Leave a Reply

You must be logged in to post a comment.