=encoding utf-8 =head1 Name lua-resty-mysql - Lua MySQL client driver for ngx_lua based on the cosocket API This library is considered production ready. =head1 Description This Lua library is a MySQL client driver for the ngx_lua nginx module: http://wiki.nginx.org/HttpLuaModule This Lua library takes advantage of ngx_lua's cosocket API, which ensures 100% nonblocking behavior. Note that at least L or L is required. Also, the L is also required. If you're using LuaJIT 2.0 with ngx_lua, then the C library is already available by default. =head1 Synopsis # you do not need the following line if you are using # the ngx_openresty bundle: lua_package_path "/path/to/lua-resty-mysql/lib/?.lua;;"; server { location /test { content_by_lua ' local mysql = require "resty.mysql" local db, err = mysql:new() if not db then ngx.say("failed to instantiate mysql: ", err) return end db:set_timeout(1000) -- 1 sec -- or connect to a unix domain socket file listened -- by a mysql server: -- local ok, err, errno, sqlstate = -- db:connect{ -- path = "/path/to/mysql.sock", -- database = "ngx_test", -- user = "ngx_test", -- password = "ngx_test" } local ok, err, errno, sqlstate = db:connect{ host = "127.0.0.1", port = 3306, database = "ngx_test", user = "ngx_test", password = "ngx_test", max_packet_size = 1024 * 1024 } if not ok then ngx.say("failed to connect: ", err, ": ", errno, " ", sqlstate) return end ngx.say("connected to mysql.") local res, err, errno, sqlstate = db:query("drop table if exists cats") if not res then ngx.say("bad result: ", err, ": ", errno, ": ", sqlstate, ".") return end res, err, errno, sqlstate = db:query("create table cats " .. "(id serial primary key, " .. "name varchar(5))") if not res then ngx.say("bad result: ", err, ": ", errno, ": ", sqlstate, ".") return end ngx.say("table cats created.") res, err, errno, sqlstate = db:query("insert into cats (name) " .. "values (\'Bob\'),(\'\'),(null)") if not res then ngx.say("bad result: ", err, ": ", errno, ": ", sqlstate, ".") return end ngx.say(res.affected_rows, " rows inserted into table cats ", "(last insert id: ", res.insert_id, ")") -- run a select query, expected about 10 rows in -- the result set: res, err, errno, sqlstate = db:query("select * from cats order by id asc", 10) if not res then ngx.say("bad result: ", err, ": ", errno, ": ", sqlstate, ".") return end local cjson = require "cjson" ngx.say("result: ", cjson.encode(res)) -- put it into the connection pool of size 100, -- with 10 seconds max idle timeout local ok, err = db:set_keepalive(10000, 100) if not ok then ngx.say("failed to set keepalive: ", err) return end -- or just close the connection right away: -- local ok, err = db:close() -- if not ok then -- ngx.say("failed to close: ", err) -- return -- end '; } } =head1 Methods =head2 new C Creates a MySQL connection object. In case of failures, returns C and a string describing the error. =head2 connect C Attempts to connect to the remote MySQL server. The C argument is a Lua table holding the following keys: =over =item * C the host name for the MySQL server. =item * C the port that the MySQL server is listening on. Default to 3306. =item * C the path of the unix socket file listened by the MySQL server. =item * C the MySQL database name. =item * C MySQL account name for login. =item * C MySQL account password for login (in clear text). =item * C the upper limit for the reply packets sent from the MySQL server (default to 1MB). =item * C If set to C, then uses SSL to connect to MySQL (default to C). If the MySQL server does not have SSL support (or just disabled), the error string "ssl disabled on server" will be returned. =item * C If set to C, then verifies the validity of the server SSL certificate (default to C). Note that you need to configure the L to specify the CA (or server) certificate used by your MySQL server. You may also need to configure L accordingly. =item * C the name for the MySQL connection pool. if omitted, an ambiguous pool name will be generated automatically with the string template C or C. (this option was first introduced in C.) =item * C when this option is set to true, then the L and L methods will return the array-of-arrays structure for the resultset, rather than the default array-of-hashes structure. =back Before actually resolving the host name and connecting to the remote backend, this method will always look up the connection pool for matched idle connections created by previous calls of this method. =head2 set_timeout C Sets the timeout (in ms) protection for subsequent operations, including the C method. =head2 set_keepalive C Puts the current MySQL connection immediately into the ngx_lua cosocket connection pool. You can specify the max idle timeout (in ms) when the connection is in the pool and the maximal size of the pool every nginx worker process. In case of success, returns C<1>. In case of errors, returns C with a string describing the error. Only call this method in the place you would have called the C method instead. Calling this method will immediately turn the current C object into the C state. Any subsequent operations other than C on the current objet will return the C error. =head2 get_reused_times C This method returns the (successfully) reused times for the current connection. In case of error, it returns C and a string describing the error. If the current connection does not come from the built-in connection pool, then this method always returns C<0>, that is, the connection has never been reused (yet). If the connection comes from the connection pool, then the return value is always non-zero. So this method can also be used to determine if the current connection comes from the pool. =head2 close C Closes the current mysql connection and returns the status. In case of success, returns C<1>. In case of errors, returns C with a string describing the error. =head2 send_query C Sends the query to the remote MySQL server without waiting for its replies. Returns the bytes successfully sent out in success and otherwise returns C and a string describing the error. You should use the L method to read the MySQL replies afterwards. =head2 read_result C C Reads in one result returned from the MySQL server. It returns a Lua table (C) describing the MySQL C or C for the query result. For queries corresponding to a result set, it returns an array holding all the rows. Each row holds key-value apirs for each data fields. For instance, { { name = "Bob", age = 32, phone = ngx.null }, { name = "Marry", age = 18, phone = "10666372"} } For queries that do not correspond to a result set, it returns a Lua table like this: { insert_id = 0, server_status = 2, warning_count = 1, affected_rows = 32, message = nil } If more results are following the current result, a second C return value will be given the string C. One should always check this (second) return value and if it is C, then she should call this method again to retrieve more results. This usually happens when the original query contains multiple statements (separated by semicolon in the same query string) or calling a MySQL procedure. See also L. In case of errors, this method returns at most 4 values: C, C, C, and C. The C return value contains a string describing the error, the C return value holds the MySQL error code (a numerical value), and finally, the C return value contains the standard SQL error code that consists of 5 characters. Note that, the C and C might be C if MySQL does not return them. The optional argument C can be used to specify an approximate number of rows for the result set. This value can be used to pre-allocate space in the resulting Lua table for the result set. By default, it takes the value 4. =head2 query C C This is a shortcut for combining the L call and the first L call. You should always check if the C return value is C in case of success because this method will only call L only once for you. See also L. =head2 server_ver C Returns the MySQL server version string, like C<"5.1.64">. You should only call this method after successfully connecting to a MySQL server, otherwise C will be returned. =head2 set_compact_arrays C Sets whether to use the "compact-arrays" structure for the resultsets returned by subsequent queries. See the C option for the C method for more details. This method was first introduced in the C release. =head1 SQL Literal Quoting It is always important to quote SQL literals properly to prevent SQL injection attacks. You can use the L function provided by ngx_lua to quote values. Here is an example: local name = ngx.unescape_uri(ngx.var.arg_name) local quoted_name = ngx.quote_sql_str(name) local sql = "select * from users where name = " .. quoted_name =head1 Multi-Resultset Support For a SQL query that produces multiple result-sets, it is always your duty to check the "again" error message returned by the L or L method calls, and keep pulling more result sets by calling the L method until no "again" error message returned (or some other errors happen). Below is a trivial example for this: local cjson = require "cjson" local mysql = require "resty.mysql" local db = mysql:new() local ok, err, errno, sqlstate = db:connect({ host = "127.0.0.1", port = 3306, database = "world", user = "monty", password = "pass"}) if not ok then ngx.log(ngx.ERR, "failed to connect: ", err, ": ", errno, " ", sqlstate) return ngx.exit(500) end res, err, errno, sqlstate = db:query("select 1; select 2; select 3;") if not res then ngx.log(ngx.ERR, "bad result #1: ", err, ": ", errno, ": ", sqlstate, ".") return ngx.exit(500) end ngx.say("result #1: ", cjson.encode(res)) local i = 2 while err == "again" do res, err, errno, sqlstate = db:read_result() if not res then ngx.log(ngx.ERR, "bad result #", i, ": ", err, ": ", errno, ": ", sqlstate, ".") return ngx.exit(500) end ngx.say("result #", i, ": ", cjson.encode(res)) i = i + 1 end local ok, err = db:set_keepalive(10000, 50) if not ok then ngx.log(ngx.ERR, "failed to set keepalive: ", err) ngx.exit(500) end This code snippet will produce the following response body data: result #1: [{"1":"1"}] result #2: [{"2":"2"}] result #3: [{"3":"3"}] =head1 Debugging It is usually convenient to use the L library to encode the return values of the MySQL query methods to JSON. For example, local cjson = require "cjson" ... local res, err, errcode, sqlstate = db:query("select * from cats") if res then print("res: ", cjson.encode(res)) end =head1 Automatic Error Logging By default the underlying L module does error logging when socket errors happen. If you are already doing proper error handling in your own Lua code, then you are recommended to disable this automatic error logging by turning off L's L directive, that is, lua_socket_log_errors off; =head1 Limitations =over =item * This library cannot be used in code contexts like init_by_luaI<, set_by_lua>, log_by_lua*, and header_filter_by_lua* where the ngx_lua cosocket API is not available. =item * The C object instance cannot be stored in a Lua variable at the Lua module level, because it will then be shared by all the concurrent requests handled by the same nginx worker process (see http://wiki.nginx.org/HttpLuaModule#Data_Sharing_within_an_Nginx_Worker ) and result in bad race conditions when concurrent requests are trying to use the same C instance. You should always initiate C objects in function local variables or in the C table. These places all have their own data copies for each request. =back =head1 Installation If you are using the ngx_openresty bundle (http://openresty.org ), then you do not need to do anything because it already includes and enables lua-resty-mysql by default. And you can just use it in your Lua code, as in local mysql = require "resty.mysql" ... If you are using your own nginx + ngx_lua build, then you need to configure the lua_package_path directive to add the path of your lua-resty-mysql source tree to ngx_lua's LUA_PATH search path, as in # nginx.conf http { lua_package_path "/path/to/lua-resty-mysql/lib/?.lua;;"; ... } Ensure that the system account running your Nginx ''worker'' proceses have enough permission to read the C<.lua> file. =head1 Community =head2 English Mailing List The L mailing list is for English speakers. =head2 Chinese Mailing List The L mailing list is for Chinese speakers. =head1 Bugs and Patches Please submit bug reports, wishlists, or patches by =over =item 1. creating a ticket on the L, =item 2. or posting to the L. =back =head1 TODO =over =item * improve the MySQL connection pool support. =item * implement the MySQL binary row data packets. =item * implement MySQL's old pre-4.0 authentication method. =item * implement MySQL server prepare and execute packets. =item * implement the data compression support in the protocol. =back =head1 Author Yichun "agentzh" Zhang (章亦春) Eagentzh@gmail.comE, CloudFlare Inc. =head1 Copyright and License This module is licensed under the BSD license. Copyright (C) 2012-2013, by Yichun "agentzh" Zhang (章亦春) Eagentzh@gmail.comE, CloudFlare Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: =over =item * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. =back =over =item * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. =back THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =head1 See Also =over =item * the ngx_lua module: http://wiki.nginx.org/HttpLuaModule =item * the MySQL wired protocol specification: http://forge.mysql.com/wiki/MySQL_Internals_ClientServer_Protocol =item * the L library =item * the L library =item * the ngx_drizzle module: http://wiki.nginx.org/HttpDrizzleModule =back