1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
|
=encoding utf-8
=head1 Name
lua-resty-mysql - Lua MySQL client driver for ngx_lua based on the cosocket API
=head1 Status
This library is considered production ready.
=head1 Description
This 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 L<ngx_lua 0.9.11|https://github.com/chaoslawful/lua-nginx-module/tags> or L<ngx_openresty 1.7.4.1|http://openresty.org/#Download> is required.
Also, the L<bit library|http://bitop.luajit.org/> is also required. If you're using LuaJIT 2 with ngx_lua, then the C<bit> 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, 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
';
}
}
=head1 Methods
=head2 new
C<syntax: db, err = mysql:new()>
Creates a MySQL connection object. In case of failures, returns C<nil> and a string describing the error.
=head2 connect
C<syntax: ok, err, errcode, sqlstate = db:connect(options)>
Attempts to connect to the remote MySQL server.
The C<options> argument is a Lua table holding the following keys:
=over
=item *
C<host>
the host name for the MySQL server.
=item *
C<port>
the port that the MySQL server is listening on. Default to 3306.
=item *
C<path>
the path of the unix socket file listened by the MySQL server.
=item *
C<database>
the MySQL database name.
=item *
C<user>
MySQL account name for login.
=item *
C<password>
MySQL account password for login (in clear text).
=item *
C<charset>
the character set used on the MySQL connection, which can be different from the default charset setting.
The following values are accepted: C<big5>, C<dec8>, C<cp850>, C<hp8>, C<koi8r>, C<latin1>, C<latin2>,
C<swe7>, C<ascii>, C<ujis>, C<sjis>, C<hebrew>, C<tis620>, C<euckr>, C<koi8u>, C<gb2312>, C<greek>,
C<cp1250>, C<gbk>, C<latin5>, C<armscii8>, C<utf8>, C<ucs2>, C<cp866>, C<keybcs2>, C<macce>,
C<macroman>, C<cp852>, C<latin7>, C<utf8mb4>, C<cp1251>, C<utf16>, C<utf16le>, C<cp1256>,
C<cp1257>, C<utf32>, C<binary>, C<geostd8>, C<cp932>, C<eucjpms>, C<gb18030>.
=item *
C<max_packet_size>
the upper limit for the reply packets sent from the MySQL server (default to 1MB).
=item *
C<ssl>
If set to C<true>, then uses SSL to connect to MySQL (default to C<false>). If the MySQL
server does not have SSL support
(or just disabled), the error string "ssl disabled on server" will be returned.
=item *
C<ssl_verify>
If set to C<true>, then verifies the validity of the server SSL certificate (default to C<false>).
Note that you need to configure the L<lua_ssl_trusted_certificate|https://github.com/openresty/lua-nginx-module#lua_ssl_trusted_certificate>
to specify the CA (or server) certificate used by your MySQL server. You may also
need to configure L<lua_ssl_verify_depth|https://github.com/openresty/lua-nginx-module#lua_ssl_verify_depth>
accordingly.
=item *
C<pool>
the name for the MySQL connection pool. if omitted, an ambiguous pool name will be generated automatically with the string template C<user:database:host:port> or C<user:database:path>. (this option was first introduced in C<v0.08>.)
=back
=over
=item *
C<pool_size>
Specifies the size of the connection pool. If omitted and no C<backlog> option was provided, no pool will be created. If omitted but C<backlog> was provided, the pool will be created with a default size equal to the value of the L<lua_socket_pool_size|https://github.com/openresty/lua-nginx-module#lua_socket_pool_size> directive. The connection pool holds up to C<pool_size> alive connections ready to be reused by subsequent calls to L<connect>, but note that there is no upper limit to the total number of opened connections outside of the pool. If you need to restrict the total number of opened connections, specify the C<backlog> option. When the connection pool would exceed its size limit, the least recently used (kept-alive) connection already in the pool will be closed to make room for the current connection. Note that the cosocket connection pool is per Nginx worker process rather than per Nginx server instance, so the size limit specified here also applies to every single Nginx worker process. Also note that the size of the connection pool cannot be changed once it has been created. Note that at least L<ngx_lua 0.10.14|https://github.com/openresty/lua-nginx-module/tags> is required to use this options.
=back
=over
=item *
C<backlog>
If specified, this module will limit the total number of opened connections for this pool. No more connections than C<pool_size> can be opened for this pool at any time. If the connection pool is full, subsequent connect operations will be queued into a queue equal to this option's value (the "backlog" queue). If the number of queued connect operations is equal to C<backlog>, subsequent connect operations will fail and return nil plus the error string C<"too many waiting connect operations">. The queued connect operations will be resumed once the number of connections in the pool is less than C<pool_size>. The queued connect operation will abort once they have been queued for more than C<connect_timeout>, controlled by L<set_timeout>, and will return nil plus the error string "timeout". Note that at least L<ngx_lua 0.10.14|https://github.com/openresty/lua-nginx-module/tags> is required to use this options.
=back
=over
=item *
C<compact_arrays>
when this option is set to true, then the L<query> and L<read_result> 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<syntax: db:set_timeout(time)>
Sets the timeout (in ms) protection for subsequent operations, including the C<connect> method.
=head2 set_keepalive
C<syntax: ok, err = db:set_keepalive(max_idle_timeout, pool_size)>
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<nil> with a string describing the error.
Only call this method in the place you would have called the C<close> method instead. Calling this method will immediately turn the current C<resty.mysql> object into the C<closed> state. Any subsequent operations other than C<connect()> on the current objet will return the C<closed> error.
=head2 get_reused_times
C<syntax: times, err = db:get_reused_times()>
This method returns the (successfully) reused times for the current connection. In case of error, it returns C<nil> 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<syntax: ok, err = db:close()>
Closes the current mysql connection and returns the status.
In case of success, returns C<1>. In case of errors, returns C<nil> with a string describing the error.
=head2 send_query
C<syntax: bytes, err = db:send_query(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 C<nil> and a string describing the error.
You should use the L<read_result> method to read the MySQL replies afterwards.
=head2 read_result
C<syntax: res, err, errcode, sqlstate = db:read_result()>
C<syntax: res, err, errcode, sqlstate = db:read_result(nrows)>
Reads in one result returned from the MySQL server.
It returns a Lua table (C<res>) describing the MySQL C<OK packet> or C<result set packet> for the query result.
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 C<err> return value will be given the string C<again>. One should always check this (second) return value and if it is C<again>, 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<Multi-Resultset Support>.
In case of errors, this method returns at most 4 values: C<nil>, C<err>, C<errcode>, and C<sqlstate>. The C<err> return value contains a string describing the error, the C<errcode> return value holds the MySQL error code (a numerical value), and finally, the C<sqlstate> return value contains the standard SQL error code that consists of 5 characters. Note that, the C<errcode> and C<sqlstate> might be C<nil> if MySQL does not return them.
The optional argument C<nrows> 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<syntax: res, err, errcode, sqlstate = db:query(query)>
C<syntax: res, err, errcode, sqlstate = db:query(query, nrows)>
This is a shortcut for combining the L<send_query> call and the first L<read_result> call.
You should always check if the C<err> return value is C<again> in case of success because this method will only call L<read_result> only once for you. See also L<Multi-Resultset Support>.
=head2 server_ver
C<syntax: str = db:server_ver()>
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<nil> will be returned.
=head2 set_compact_arrays
C<syntax: db:set_compact_arrays(boolean)>
Sets whether to use the "compact-arrays" structure for the resultsets returned by subsequent queries. See the C<compact_arrays> option for the C<connect> method for more details.
This method was first introduced in the C<v0.09> release.
=head1 SQL Literal Quoting
It is always important to quote SQL literals properly to prevent SQL injection attacks. You can use the
L<ngx.quote_sql_str|https://github.com/openresty/lua-nginx-module#ngxquote_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
=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<query> or L<read_result> method calls, and keep pulling more result sets by calling the L<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:
result #1: [{"1":"1"}]
result #2: [{"2":"2"}]
result #3: [{"3":"3"}]
=head1 Debugging
It is usually convenient to use the L<lua-cjson|http://www.kyne.com.au/~mark/software/lua-cjson.php> 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<ngx_lua|https://github.com/openresty/lua-nginx-module> 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<ngx_lua|https://github.com/openresty/lua-nginx-module>'s L<lua_socket_log_errors|https://github.com/openresty/lua-nginx-module#lua_socket_log_errors> 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<resty.mysql> 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
https://github.com/openresty/lua-nginx-module#data-sharing-within-an-nginx-worker ) and
result in bad race conditions when concurrent requests are trying to use the same C<resty.mysql> instance.
You should always initiate C<resty.mysql> objects in function local
variables or in the C<ngx.ctx> table. These places all have their own data copies for
each request.
=back
=head1 More Authentication Method Support
By default, Of all authentication method, only L<Old Password Authentication(mysql_old_password)|https://dev.mysql.com/doc/internals/en/old-password-authentication.html> and L<Secure Password Authentication(mysql_native_password)|https://dev.mysql.com/doc/internals/en/secure-password-authentication.html> are suppored. If the server requires L<sha256_password|https://dev.mysql.com/doc/internals/en/sha256.html> or cache_sha2_password, an error like C<auth plugin caching_sha2_password or sha256_password are not supported because resty.rsa is not installed> may be returned.
Need L<lua-resty-rsa|https://github.com/spacewander/lua-resty-rsa> when using the C<sha256_password> and C<cache_sha2_password>.
=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<openresty-en|https://groups.google.com/group/openresty-en> mailing list is for English speakers.
=head2 Chinese Mailing List
The L<openresty|https://groups.google.com/group/openresty> 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<GitHub Issue Tracker|http://github.com/agentzh/lua-resty-mysql/issues>,
=item 2.
or posting to the L<OpenResty community|https://github.com/openresty/lua-nginx-module#community>.
=back
=head1 TODO
=over
=item *
improve the MySQL connection pool support.
=item *
implement the MySQL binary row data packets.
=item *
implement MySQL server prepare and execute packets.
=item *
implement the data compression support in the protocol.
=back
=head1 Author
Yichun "agentzh" Zhang (章亦春) E<lt>agentzh@gmail.comE<gt>, OpenResty Inc.
=head1 Copyright and License
This module is licensed under the BSD license.
Copyright (C) 2012-2018, by Yichun "agentzh" Zhang (章亦春) E<lt>agentzh@gmail.comE<gt>, 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:
=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: https://github.com/openresty/lua-nginx-module
=item *
the MySQL wired protocol specification: http://forge.mysql.com/wiki/MySQL_Internals_ClientServer_Protocol
=item *
the L<lua-resty-memcached|https://github.com/agentzh/lua-resty-memcached> library
=item *
the L<lua-resty-redis|https://github.com/agentzh/lua-resty-redis> library
=item *
the ngx_drizzle module: https://github.com/openresty/drizzle-nginx-module
=back
|