开源软件名称(OpenSource Name):openresty/lua-resty-mysql开源软件地址(OpenSource Url):https://github.com/openresty/lua-resty-mysql开源编程语言(OpenSource Language):Lua 84.4%开源软件介绍(OpenSource Introduction):Namelua-resty-mysql - Lua MySQL client driver for ngx_lua based on the cosocket API Table of Contents
StatusThis library is considered production ready. DescriptionThis Lua library is a MySQL client driver for the ngx_lua nginx module: https://github.com/openresty/lua-nginx-module This Lua library takes advantage of ngx_lua's cosocket API, which ensures 100% nonblocking behavior. Note that at least ngx_lua 0.9.11 or ngx_openresty 1.7.4.1 is required. Also, the bit library is also required. If you're using LuaJIT 2 with ngx_lua, then the 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, errcode, sqlstate =
-- db:connect{
-- path = "/path/to/mysql.sock",
-- database = "ngx_test",
-- user = "ngx_test",
-- password = "ngx_test" }
local ok, err, errcode, sqlstate = db:connect{
host = "127.0.0.1",
port = 3306,
database = "ngx_test",
user = "ngx_test",
password = "ngx_test",
charset = "utf8",
max_packet_size = 1024 * 1024,
}
if not ok then
ngx.say("failed to connect: ", err, ": ", errcode, " ", sqlstate)
return
end
ngx.say("connected to mysql.")
local res, err, errcode, sqlstate =
db:query("drop table if exists cats")
if not res then
ngx.say("bad result: ", err, ": ", errcode, ": ", sqlstate, ".")
return
end
res, err, errcode, sqlstate =
db:query("create table cats "
.. "(id serial primary key, "
.. "name varchar(5))")
if not res then
ngx.say("bad result: ", err, ": ", errcode, ": ", sqlstate, ".")
return
end
ngx.say("table cats created.")
res, err, errcode, sqlstate =
db:query("insert into cats (name) "
.. "values (\'Bob\'),(\'\'),(null)")
if not res then
ngx.say("bad result: ", err, ": ", errcode, ": ", 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, errcode, sqlstate =
db:query("select * from cats order by id asc", 10)
if not res then
ngx.say("bad result: ", err, ": ", errcode, ": ", 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
';
}
} Methodsnew
Creates a MySQL connection object. In case of failures, returns connect
Attempts to connect to the remote MySQL server. The
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. set_timeout
Sets the timeout (in ms) protection for subsequent operations, including the set_keepalive
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 Only call this method in the place you would have called the get_reused_times
This method returns the (successfully) reused times for the current connection. In case of error, it returns If the current connection does not come from the built-in connection pool, then this method always returns close
Closes the current mysql connection and returns the status. In case of success, returns send_query
Sends the query to the remote MySQL server without waiting for its replies. Returns the bytes successfully sent out in success and otherwise returns You should use the read_result method to read the MySQL replies afterwards. read_result
Reads in one result returned from the MySQL server. It returns a Lua table ( For queries corresponding to a result set, it returns an array holding all the rows. Each row holds key-value pairs 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 In case of errors, this method returns at most 4 values: The optional argument query
This is a shortcut for combining the send_query call and the first read_result call. You should always check if the server_ver
Returns the MySQL server version string, like You should only call this method after successfully connecting to a MySQL server, otherwise set_compact_arrays
Sets whether to use the "compact-arrays" structure for the resultsets returned by subsequent queries. See the This method was first introduced in the SQL Literal QuotingIt is always important to quote SQL literals properly to prevent SQL injection attacks. You can use the ngx.quote_sql_str 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 Multi-Resultset SupportFor a SQL query that produces multiple result-sets, it is always your duty to check the "again" error message returned by the query or read_result method calls, and keep pulling more result sets by calling the read_result 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, errcode, 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, ": ", errcode, " ", sqlstate)
return ngx.exit(500)
end
res, err, errcode, sqlstate = db:query("select 1; select 2; select 3;")
if not res then
ngx.log(ngx.ERR, "bad result #1: ", err, ": ", errcode, ": ", sqlstate, ".")
return ngx.exit(500)
end
ngx.say("result #1: ", cjson.encode(res))
local i = 2
while err == "again" do
res, err, errcode, sqlstate = db:read_result()
if not res then
ngx.log(ngx.ERR, "bad result #", i, ": ", err, ": ", errcode, ": ", 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:
DebuggingIt is usually convenient to use the lua-cjson 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 Automatic Error LoggingBy default the underlying ngx_lua 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 ngx_lua's lua_socket_log_errors directive, that is, lua_socket_log_errors off; Limitations
More Authentication Method SupportBy default, Of all authentication method, only Old Password Authentication(mysql_old_password) and Secure Password Authentication(mysql_native_password) are suppored. If the server requires sha256_password or cache_sha2_password, an error like Need lua-resty-rsa when using the InstallationIf 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 CommunityEnglish Mailing ListThe openresty-en mailing list is for English speakers. Chinese Mailing ListThe openresty mailing list is for Chinese speakers. Bugs and PatchesPlease submit bug reports, wishlists, or patches by
TODO
AuthorYichun "agentzh" Zhang (章亦春) agentzh@gmail.com, OpenResty Inc. Copyright and LicenseThis module is licensed under the BSD license. Copyright (C) 2012-2018, by Yichun "agentzh" Zhang (章亦春) agentzh@gmail.com, OpenResty 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:
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论