-
Notifications
You must be signed in to change notification settings - Fork 548
/
Copy pathclient.c
1415 lines (1196 loc) · 40.2 KB
/
client.c
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
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <mysql2_ext.h>
#include <time.h>
#include <errno.h>
#ifndef _WIN32
#include <sys/types.h>
#include <sys/socket.h>
#endif
#ifndef _MSC_VER
#include <unistd.h>
#endif
#include <fcntl.h>
#include "wait_for_single_fd.h"
#include "mysql_enc_name_to_ruby.h"
VALUE cMysql2Client;
extern VALUE mMysql2, cMysql2Error;
static VALUE sym_id, sym_version, sym_header_version, sym_async, sym_symbolize_keys, sym_as, sym_array, sym_stream;
static ID intern_merge, intern_merge_bang, intern_error_number_eql, intern_sql_state_eql;
#ifndef HAVE_RB_HASH_DUP
static VALUE rb_hash_dup(VALUE other) {
return rb_funcall(rb_cHash, rb_intern("[]"), 1, other);
}
#endif
#define REQUIRE_INITIALIZED(wrapper) \
if (!wrapper->initialized) { \
rb_raise(cMysql2Error, "MySQL client is not initialized"); \
}
#define REQUIRE_CONNECTED(wrapper) \
REQUIRE_INITIALIZED(wrapper) \
if (!wrapper->connected && !wrapper->reconnect_enabled) { \
rb_raise(cMysql2Error, "closed MySQL connection"); \
}
#define REQUIRE_NOT_CONNECTED(wrapper) \
REQUIRE_INITIALIZED(wrapper) \
if (wrapper->connected) { \
rb_raise(cMysql2Error, "MySQL connection is already open"); \
}
#define MARK_CONN_INACTIVE(conn) \
wrapper->active_thread = Qnil;
#define GET_CLIENT(self) \
mysql_client_wrapper *wrapper; \
Data_Get_Struct(self, mysql_client_wrapper, wrapper)
/*
* compatability with mysql-connector-c, where LIBMYSQL_VERSION is the correct
* variable to use, but MYSQL_SERVER_VERSION gives the correct numbers when
* linking against the server itself
*/
#ifdef LIBMYSQL_VERSION
#define MYSQL_LINK_VERSION LIBMYSQL_VERSION
#else
#define MYSQL_LINK_VERSION MYSQL_SERVER_VERSION
#endif
/*
* used to pass all arguments to mysql_real_connect while inside
* rb_thread_call_without_gvl
*/
struct nogvl_connect_args {
MYSQL *mysql;
const char *host;
const char *user;
const char *passwd;
const char *db;
unsigned int port;
const char *unix_socket;
unsigned long client_flag;
};
/*
* used to pass all arguments to mysql_send_query while inside
* rb_thread_call_without_gvl
*/
struct nogvl_send_query_args {
MYSQL *mysql;
VALUE sql;
const char *sql_ptr;
long sql_len;
mysql_client_wrapper *wrapper;
};
/*
* used to pass all arguments to mysql_select_db while inside
* rb_thread_call_without_gvl
*/
struct nogvl_select_db_args {
MYSQL *mysql;
char *db;
};
/*
* non-blocking mysql_*() functions that we won't be wrapping since
* they do not appear to hit the network nor issue any interruptible
* or blocking system calls.
*
* - mysql_affected_rows()
* - mysql_error()
* - mysql_fetch_fields()
* - mysql_fetch_lengths() - calls cli_fetch_lengths or emb_fetch_lengths
* - mysql_field_count()
* - mysql_get_client_info()
* - mysql_get_client_version()
* - mysql_get_server_info()
* - mysql_get_server_version()
* - mysql_insert_id()
* - mysql_num_fields()
* - mysql_num_rows()
* - mysql_options()
* - mysql_real_escape_string()
* - mysql_ssl_set()
*/
static void rb_mysql_client_mark(void * wrapper) {
mysql_client_wrapper * w = wrapper;
if (w) {
rb_gc_mark(w->encoding);
rb_gc_mark(w->active_thread);
}
}
static VALUE rb_raise_mysql2_error(mysql_client_wrapper *wrapper) {
VALUE rb_error_msg = rb_str_new2(mysql_error(wrapper->client));
VALUE rb_sql_state = rb_tainted_str_new2(mysql_sqlstate(wrapper->client));
VALUE e;
#ifdef HAVE_RUBY_ENCODING_H
rb_enc_associate(rb_error_msg, rb_utf8_encoding());
rb_enc_associate(rb_sql_state, rb_usascii_encoding());
#endif
e = rb_funcall(cMysql2Error, rb_intern("new"), 2, rb_error_msg, LONG2FIX(wrapper->server_version));
rb_funcall(e, intern_error_number_eql, 1, UINT2NUM(mysql_errno(wrapper->client)));
rb_funcall(e, intern_sql_state_eql, 1, rb_sql_state);
rb_exc_raise(e);
return Qnil;
}
static void *nogvl_init(void *ptr) {
MYSQL *client;
mysql_client_wrapper *wrapper = (mysql_client_wrapper *)ptr;
/* may initialize embedded server and read /etc/services off disk */
client = mysql_init(wrapper->client);
if (client) mysql2_set_local_infile(client, wrapper);
return (void*)(client ? Qtrue : Qfalse);
}
static void *nogvl_connect(void *ptr) {
struct nogvl_connect_args *args = ptr;
MYSQL *client;
client = mysql_real_connect(args->mysql, args->host,
args->user, args->passwd,
args->db, args->port, args->unix_socket,
args->client_flag);
return (void *)(client ? Qtrue : Qfalse);
}
#ifndef _WIN32
/*
* Redirect clientfd to /dev/null for mysql_close and SSL_close to write,
* shutdown, and close. The hack is needed to prevent shutdown() from breaking
* a socket that may be in use by the parent or other processes after fork.
*
* /dev/null is used to absorb writes; previously a dummy socket was used, but
* it could not abosrb writes and caused openssl to go into an infinite loop.
*
* Returns Qtrue or Qfalse (success or failure)
*
* Note: if this function is needed on Windows, use "nul" instead of "/dev/null"
*/
static VALUE invalidate_fd(int clientfd)
{
#ifdef O_CLOEXEC
/* Atomically set CLOEXEC on the new FD in case another thread forks */
int sockfd = open("/dev/null", O_RDWR | O_CLOEXEC);
#else
/* Well we don't have O_CLOEXEC, trigger the fallback code below */
int sockfd = -1;
#endif
if (sockfd < 0) {
/* Either O_CLOEXEC wasn't defined at compile time, or it was defined at
* compile time, but isn't available at run-time. So we'll just be quick
* about setting FD_CLOEXEC now.
*/
int flags;
sockfd = open("/dev/null", O_RDWR);
flags = fcntl(sockfd, F_GETFD);
/* Do the flags dance in case there are more defined flags in the future */
if (flags != -1) {
flags |= FD_CLOEXEC;
fcntl(sockfd, F_SETFD, flags);
}
}
if (sockfd < 0) {
/* Cannot raise here, because one or both of the following may be true:
* a) we have no GVL (in C Ruby)
* b) are running as a GC finalizer
*/
return Qfalse;
}
dup2(sockfd, clientfd);
close(sockfd);
return Qtrue;
}
#endif /* _WIN32 */
static void *nogvl_close(void *ptr) {
mysql_client_wrapper *wrapper;
wrapper = ptr;
if (wrapper->connected) {
wrapper->active_thread = Qnil;
wrapper->connected = 0;
mysql_close(wrapper->client); /* only used to free memory at this point */
}
return NULL;
}
static void rb_mysql_client_free(void *ptr) {
mysql_client_wrapper *wrapper = (mysql_client_wrapper *)ptr;
decr_mysql2_client(wrapper);
}
void decr_mysql2_client(mysql_client_wrapper *wrapper)
{
wrapper->refcount--;
if (wrapper->refcount == 0) {
#ifndef _WIN32
if (wrapper->connected) {
/* Invalidate the socket before calling mysql_close(). This prevents
* mysql_close() from sending a mysql-QUIT or from calling shutdown() on
* the socket. The difference is that invalidate_fd will drop this
* process's reference to the socket only, while a QUIT or shutdown()
* would render the underlying connection unusable, interrupting other
* processes which share this object across a fork().
*/
if (invalidate_fd(wrapper->client->net.fd) == Qfalse) {
fprintf(stderr, "[WARN] mysql2 failed to invalidate FD safely, leaking some memory\n");
close(wrapper->client->net.fd);
return NULL;
}
}
#endif
nogvl_close(wrapper);
xfree(wrapper->client);
xfree(wrapper);
}
}
static VALUE allocate(VALUE klass) {
VALUE obj;
mysql_client_wrapper * wrapper;
obj = Data_Make_Struct(klass, mysql_client_wrapper, rb_mysql_client_mark, rb_mysql_client_free, wrapper);
wrapper->encoding = Qnil;
wrapper->active_thread = Qnil;
wrapper->server_version = 0;
wrapper->reconnect_enabled = 0;
wrapper->connect_timeout = 0;
wrapper->connected = 0; /* means that a database connection is open */
wrapper->initialized = 0; /* means that that the wrapper is initialized */
wrapper->refcount = 1;
wrapper->client = (MYSQL*)xmalloc(sizeof(MYSQL));
return obj;
}
/* call-seq:
* Mysql2::Client.escape(string)
*
* Escape +string+ so that it may be used in a SQL statement.
* Note that this escape method is not connection encoding aware.
* If you need encoding support use Mysql2::Client#escape instead.
*/
static VALUE rb_mysql_client_escape(RB_MYSQL_UNUSED VALUE klass, VALUE str) {
unsigned char *newStr;
VALUE rb_str;
unsigned long newLen, oldLen;
Check_Type(str, T_STRING);
oldLen = RSTRING_LEN(str);
newStr = xmalloc(oldLen*2+1);
newLen = mysql_escape_string((char *)newStr, RSTRING_PTR(str), oldLen);
if (newLen == oldLen) {
/* no need to return a new ruby string if nothing changed */
xfree(newStr);
return str;
} else {
rb_str = rb_str_new((const char*)newStr, newLen);
#ifdef HAVE_RUBY_ENCODING_H
rb_enc_copy(rb_str, str);
#endif
xfree(newStr);
return rb_str;
}
}
static VALUE rb_mysql_client_warning_count(VALUE self) {
unsigned int warning_count;
GET_CLIENT(self);
warning_count = mysql_warning_count(wrapper->client);
return UINT2NUM(warning_count);
}
static VALUE rb_mysql_info(VALUE self) {
const char *info;
VALUE rb_str;
GET_CLIENT(self);
info = mysql_info(wrapper->client);
if (info == NULL) {
return Qnil;
}
rb_str = rb_str_new2(info);
#ifdef HAVE_RUBY_ENCODING_H
rb_enc_associate(rb_str, rb_utf8_encoding());
#endif
return rb_str;
}
static VALUE rb_connect(VALUE self, VALUE user, VALUE pass, VALUE host, VALUE port, VALUE database, VALUE socket, VALUE flags) {
struct nogvl_connect_args args;
time_t start_time, end_time;
unsigned int elapsed_time, connect_timeout;
VALUE rv;
GET_CLIENT(self);
args.host = NIL_P(host) ? NULL : StringValueCStr(host);
args.unix_socket = NIL_P(socket) ? NULL : StringValueCStr(socket);
args.port = NIL_P(port) ? 0 : NUM2INT(port);
args.user = NIL_P(user) ? NULL : StringValueCStr(user);
args.passwd = NIL_P(pass) ? NULL : StringValueCStr(pass);
args.db = NIL_P(database) ? NULL : StringValueCStr(database);
args.mysql = wrapper->client;
args.client_flag = NUM2ULONG(flags);
if (wrapper->connect_timeout)
time(&start_time);
rv = (VALUE) rb_thread_call_without_gvl(nogvl_connect, &args, RUBY_UBF_IO, 0);
if (rv == Qfalse) {
while (rv == Qfalse && errno == EINTR) {
if (wrapper->connect_timeout) {
time(&end_time);
/* avoid long connect timeout from system time changes */
if (end_time < start_time)
start_time = end_time;
elapsed_time = end_time - start_time;
/* avoid an early timeout due to time truncating milliseconds off the start time */
if (elapsed_time > 0)
elapsed_time--;
if (elapsed_time >= wrapper->connect_timeout)
break;
connect_timeout = wrapper->connect_timeout - elapsed_time;
mysql_options(wrapper->client, MYSQL_OPT_CONNECT_TIMEOUT, &connect_timeout);
}
errno = 0;
rv = (VALUE) rb_thread_call_without_gvl(nogvl_connect, &args, RUBY_UBF_IO, 0);
}
/* restore the connect timeout for reconnecting */
if (wrapper->connect_timeout)
mysql_options(wrapper->client, MYSQL_OPT_CONNECT_TIMEOUT, &wrapper->connect_timeout);
if (rv == Qfalse)
return rb_raise_mysql2_error(wrapper);
}
wrapper->server_version = mysql_get_server_version(wrapper->client);
wrapper->connected = 1;
return self;
}
/*
* Terminate the connection; call this when the connection is no longer needed.
* The garbage collector can close the connection, but doing so emits an
* "Aborted connection" error on the server and increments the Aborted_clients
* status variable.
*
* @see http://dev.mysql.com/doc/en/communication-errors.html
* @see https://github.com/brianmario/mysql2/pull/663
* @return [void]
*
*/
static VALUE rb_mysql_client_close(VALUE self) {
GET_CLIENT(self);
if (wrapper->connected) {
rb_thread_call_without_gvl(nogvl_close, wrapper, RUBY_UBF_IO, 0);
}
return Qnil;
}
/*
* mysql_send_query is unlikely to block since most queries are small
* enough to fit in a socket buffer, but sometimes large UPDATE and
* INSERTs will cause the process to block
*/
static void *nogvl_send_query(void *ptr) {
struct nogvl_send_query_args *args = ptr;
int rv;
rv = mysql_send_query(args->mysql, args->sql_ptr, args->sql_len);
return (void*)(rv == 0 ? Qtrue : Qfalse);
}
static VALUE do_send_query(void *args) {
struct nogvl_send_query_args *query_args = args;
mysql_client_wrapper *wrapper = query_args->wrapper;
if ((VALUE)rb_thread_call_without_gvl(nogvl_send_query, args, RUBY_UBF_IO, 0) == Qfalse) {
/* an error occurred, we're not active anymore */
MARK_CONN_INACTIVE(self);
return rb_raise_mysql2_error(wrapper);
}
return Qnil;
}
/*
* even though we did rb_thread_select before calling this, a large
* response can overflow the socket buffers and cause us to eventually
* block while calling mysql_read_query_result
*/
static void *nogvl_read_query_result(void *ptr) {
MYSQL * client = ptr;
my_bool res = mysql_read_query_result(client);
return (void *)(res == 0 ? Qtrue : Qfalse);
}
static void *nogvl_do_result(void *ptr, char use_result) {
mysql_client_wrapper *wrapper;
MYSQL_RES *result;
wrapper = (mysql_client_wrapper *)ptr;
if (use_result) {
result = mysql_use_result(wrapper->client);
} else {
result = mysql_store_result(wrapper->client);
}
/* once our result is stored off, this connection is
ready for another command to be issued */
wrapper->active_thread = Qnil;
return result;
}
/* mysql_store_result may (unlikely) read rows off the socket */
static void *nogvl_store_result(void *ptr) {
return nogvl_do_result(ptr, 0);
}
static void *nogvl_use_result(void *ptr) {
return nogvl_do_result(ptr, 1);
}
/* call-seq:
* client.async_result
*
* Returns the result for the last async issued query.
*/
static VALUE rb_mysql_client_async_result(VALUE self) {
MYSQL_RES * result;
VALUE resultObj;
VALUE current, is_streaming;
GET_CLIENT(self);
/* if we're not waiting on a result, do nothing */
if (NIL_P(wrapper->active_thread))
return Qnil;
REQUIRE_CONNECTED(wrapper);
if ((VALUE)rb_thread_call_without_gvl(nogvl_read_query_result, wrapper->client, RUBY_UBF_IO, 0) == Qfalse) {
/* an error occurred, mark this connection inactive */
MARK_CONN_INACTIVE(self);
return rb_raise_mysql2_error(wrapper);
}
is_streaming = rb_hash_aref(rb_iv_get(self, "@current_query_options"), sym_stream);
if (is_streaming == Qtrue) {
result = (MYSQL_RES *)rb_thread_call_without_gvl(nogvl_use_result, wrapper, RUBY_UBF_IO, 0);
} else {
result = (MYSQL_RES *)rb_thread_call_without_gvl(nogvl_store_result, wrapper, RUBY_UBF_IO, 0);
}
if (result == NULL) {
if (mysql_errno(wrapper->client) != 0) {
MARK_CONN_INACTIVE(self);
rb_raise_mysql2_error(wrapper);
}
/* no data and no error, so query was not a SELECT */
return Qnil;
}
current = rb_hash_dup(rb_iv_get(self, "@current_query_options"));
RB_GC_GUARD(current);
Check_Type(current, T_HASH);
resultObj = rb_mysql_result_to_obj(self, wrapper->encoding, current, result);
return resultObj;
}
#ifndef _WIN32
struct async_query_args {
int fd;
VALUE self;
};
static VALUE disconnect_and_raise(VALUE self, VALUE error) {
GET_CLIENT(self);
wrapper->active_thread = Qnil;
wrapper->connected = 0;
/* Invalidate the MySQL socket to prevent further communication.
* The GC will come along later and call mysql_close to free it.
*/
if (invalidate_fd(wrapper->client->net.fd) == Qfalse) {
fprintf(stderr, "[WARN] mysql2 failed to invalidate FD safely, closing unsafely\n");
close(wrapper->client->net.fd);
}
rb_exc_raise(error);
return Qnil;
}
static VALUE do_query(void *args) {
struct async_query_args *async_args;
struct timeval tv;
struct timeval* tvp;
long int sec;
int retval;
VALUE read_timeout;
async_args = (struct async_query_args *)args;
read_timeout = rb_iv_get(async_args->self, "@read_timeout");
tvp = NULL;
if (!NIL_P(read_timeout)) {
Check_Type(read_timeout, T_FIXNUM);
tvp = &tv;
sec = FIX2INT(read_timeout);
/* TODO: support partial seconds?
also, this check is here for sanity, we also check up in Ruby */
if (sec >= 0) {
tvp->tv_sec = sec;
} else {
rb_raise(cMysql2Error, "read_timeout must be a positive integer, you passed %ld", sec);
}
tvp->tv_usec = 0;
}
for(;;) {
retval = rb_wait_for_single_fd(async_args->fd, RB_WAITFD_IN, tvp);
if (retval == 0) {
rb_raise(cMysql2Error, "Timeout waiting for a response from the last query. (waited %d seconds)", FIX2INT(read_timeout));
}
if (retval < 0) {
rb_sys_fail(0);
}
if (retval > 0) {
break;
}
}
return Qnil;
}
#else
static VALUE finish_and_mark_inactive(void *args) {
VALUE self;
MYSQL_RES *result;
self = (VALUE)args;
GET_CLIENT(self);
if (!NIL_P(wrapper->active_thread)) {
/* if we got here, the result hasn't been read off the wire yet
so lets do that and then throw it away because we have no way
of getting it back up to the caller from here */
result = (MYSQL_RES *)rb_thread_call_without_gvl(nogvl_store_result, wrapper, RUBY_UBF_IO, 0);
mysql_free_result(result);
wrapper->active_thread = Qnil;
}
return Qnil;
}
#endif
/* call-seq:
* client.abandon_results!
*
* When using MULTI_STATEMENTS support, calling this will throw
* away any unprocessed results as fast as it can in order to
* put the connection back into a state where queries can be issued
* again.
*/
static VALUE rb_mysql_client_abandon_results(VALUE self) {
MYSQL_RES *result;
int ret;
GET_CLIENT(self);
while (mysql_more_results(wrapper->client) == 1) {
ret = mysql_next_result(wrapper->client);
if (ret > 0) {
rb_raise_mysql2_error(wrapper);
}
result = (MYSQL_RES *)rb_thread_call_without_gvl(nogvl_store_result, wrapper, RUBY_UBF_IO, 0);
if (result != NULL) {
mysql_free_result(result);
}
}
return Qnil;
}
/* call-seq:
* client.query(sql, options = {})
*
* Query the database with +sql+, with optional +options+. For the possible
* options, see @@default_query_options on the Mysql2::Client class.
*/
static VALUE rb_query(VALUE self, VALUE sql, VALUE current) {
#ifndef _WIN32
struct async_query_args async_args;
#endif
struct nogvl_send_query_args args;
VALUE thread_current = rb_thread_current();
GET_CLIENT(self);
REQUIRE_CONNECTED(wrapper);
args.mysql = wrapper->client;
RB_GC_GUARD(current);
Check_Type(current, T_HASH);
rb_iv_set(self, "@current_query_options", current);
Check_Type(sql, T_STRING);
#ifdef HAVE_RUBY_ENCODING_H
/* ensure the string is in the encoding the connection is expecting */
args.sql = rb_str_export_to_enc(sql, rb_to_encoding(wrapper->encoding));
#else
args.sql = sql;
#endif
args.sql_ptr = RSTRING_PTR(args.sql);
args.sql_len = RSTRING_LEN(args.sql);
/* see if this connection is still waiting on a result from a previous query */
if (NIL_P(wrapper->active_thread)) {
/* mark this connection active */
wrapper->active_thread = thread_current;
} else if (wrapper->active_thread == thread_current) {
rb_raise(cMysql2Error, "This connection is still waiting for a result, try again once you have the result");
} else {
VALUE inspect = rb_inspect(wrapper->active_thread);
const char *thr = StringValueCStr(inspect);
rb_raise(cMysql2Error, "This connection is in use by: %s", thr);
RB_GC_GUARD(inspect);
}
args.wrapper = wrapper;
#ifndef _WIN32
rb_rescue2(do_send_query, (VALUE)&args, disconnect_and_raise, self, rb_eException, (VALUE)0);
if (rb_hash_aref(current, sym_async) == Qtrue) {
return Qnil;
} else {
async_args.fd = wrapper->client->net.fd;
async_args.self = self;
rb_rescue2(do_query, (VALUE)&async_args, disconnect_and_raise, self, rb_eException, (VALUE)0);
return rb_mysql_client_async_result(self);
}
#else
do_send_query(&args);
/* this will just block until the result is ready */
return rb_ensure(rb_mysql_client_async_result, self, finish_and_mark_inactive, self);
#endif
}
/* call-seq:
* client.escape(string)
*
* Escape +string+ so that it may be used in a SQL statement.
*/
static VALUE rb_mysql_client_real_escape(VALUE self, VALUE str) {
unsigned char *newStr;
VALUE rb_str;
unsigned long newLen, oldLen;
#ifdef HAVE_RUBY_ENCODING_H
rb_encoding *default_internal_enc;
rb_encoding *conn_enc;
#endif
GET_CLIENT(self);
REQUIRE_CONNECTED(wrapper);
Check_Type(str, T_STRING);
#ifdef HAVE_RUBY_ENCODING_H
default_internal_enc = rb_default_internal_encoding();
conn_enc = rb_to_encoding(wrapper->encoding);
/* ensure the string is in the encoding the connection is expecting */
str = rb_str_export_to_enc(str, conn_enc);
#endif
oldLen = RSTRING_LEN(str);
newStr = xmalloc(oldLen*2+1);
newLen = mysql_real_escape_string(wrapper->client, (char *)newStr, RSTRING_PTR(str), oldLen);
if (newLen == oldLen) {
/* no need to return a new ruby string if nothing changed */
#ifdef HAVE_RUBY_ENCODING_H
if (default_internal_enc) {
str = rb_str_export_to_enc(str, default_internal_enc);
}
#endif
xfree(newStr);
return str;
} else {
rb_str = rb_str_new((const char*)newStr, newLen);
#ifdef HAVE_RUBY_ENCODING_H
rb_enc_associate(rb_str, conn_enc);
if (default_internal_enc) {
rb_str = rb_str_export_to_enc(rb_str, default_internal_enc);
}
#endif
xfree(newStr);
return rb_str;
}
}
static VALUE _mysql_client_options(VALUE self, int opt, VALUE value) {
int result;
const void *retval = NULL;
unsigned int intval = 0;
const char * charval = NULL;
my_bool boolval;
GET_CLIENT(self);
REQUIRE_NOT_CONNECTED(wrapper);
if (NIL_P(value))
return Qfalse;
switch(opt) {
case MYSQL_OPT_CONNECT_TIMEOUT:
intval = NUM2UINT(value);
retval = &intval;
break;
case MYSQL_OPT_READ_TIMEOUT:
intval = NUM2UINT(value);
retval = &intval;
break;
case MYSQL_OPT_WRITE_TIMEOUT:
intval = NUM2UINT(value);
retval = &intval;
break;
case MYSQL_OPT_LOCAL_INFILE:
intval = (value == Qfalse ? 0 : 1);
retval = &intval;
break;
case MYSQL_OPT_RECONNECT:
boolval = (value == Qfalse ? 0 : 1);
retval = &boolval;
break;
case MYSQL_SECURE_AUTH:
boolval = (value == Qfalse ? 0 : 1);
retval = &boolval;
break;
case MYSQL_READ_DEFAULT_FILE:
charval = (const char *)StringValueCStr(value);
retval = charval;
break;
case MYSQL_READ_DEFAULT_GROUP:
charval = (const char *)StringValueCStr(value);
retval = charval;
break;
case MYSQL_INIT_COMMAND:
charval = (const char *)StringValueCStr(value);
retval = charval;
break;
default:
return Qfalse;
}
result = mysql_options(wrapper->client, opt, retval);
/* Zero means success */
if (result != 0) {
rb_warn("%s\n", mysql_error(wrapper->client));
} else {
/* Special case for options that are stored in the wrapper struct */
switch (opt) {
case MYSQL_OPT_RECONNECT:
wrapper->reconnect_enabled = boolval;
break;
case MYSQL_OPT_CONNECT_TIMEOUT:
wrapper->connect_timeout = intval;
break;
}
}
return (result == 0) ? Qtrue : Qfalse;
}
/* call-seq:
* client.info
*
* Returns a string that represents the client library version.
*/
static VALUE rb_mysql_client_info(RB_MYSQL_UNUSED VALUE klass) {
VALUE version_info, version, header_version;
version_info = rb_hash_new();
version = rb_str_new2(mysql_get_client_info());
header_version = rb_str_new2(MYSQL_LINK_VERSION);
#ifdef HAVE_RUBY_ENCODING_H
rb_enc_associate(version, rb_usascii_encoding());
rb_enc_associate(header_version, rb_usascii_encoding());
#endif
rb_hash_aset(version_info, sym_id, LONG2NUM(mysql_get_client_version()));
rb_hash_aset(version_info, sym_version, version);
rb_hash_aset(version_info, sym_header_version, header_version);
return version_info;
}
/* call-seq:
* client.server_info
*
* Returns a string that represents the server version number
*/
static VALUE rb_mysql_client_server_info(VALUE self) {
VALUE version, server_info;
#ifdef HAVE_RUBY_ENCODING_H
rb_encoding *default_internal_enc;
rb_encoding *conn_enc;
#endif
GET_CLIENT(self);
REQUIRE_CONNECTED(wrapper);
#ifdef HAVE_RUBY_ENCODING_H
default_internal_enc = rb_default_internal_encoding();
conn_enc = rb_to_encoding(wrapper->encoding);
#endif
version = rb_hash_new();
rb_hash_aset(version, sym_id, LONG2FIX(mysql_get_server_version(wrapper->client)));
server_info = rb_str_new2(mysql_get_server_info(wrapper->client));
#ifdef HAVE_RUBY_ENCODING_H
rb_enc_associate(server_info, conn_enc);
if (default_internal_enc) {
server_info = rb_str_export_to_enc(server_info, default_internal_enc);
}
#endif
rb_hash_aset(version, sym_version, server_info);
return version;
}
/* call-seq:
* client.socket
*
* Return the file descriptor number for this client.
*/
static VALUE rb_mysql_client_socket(VALUE self) {
#ifndef _WIN32
GET_CLIENT(self);
REQUIRE_CONNECTED(wrapper);
return INT2NUM(wrapper->client->net.fd);
#else
rb_raise(cMysql2Error, "Raw access to the mysql file descriptor isn't supported on Windows");
#endif
}
/* call-seq:
* client.last_id
*
* Returns the value generated for an AUTO_INCREMENT column by the previous INSERT or UPDATE
* statement.
*/
static VALUE rb_mysql_client_last_id(VALUE self) {
GET_CLIENT(self);
REQUIRE_CONNECTED(wrapper);
return ULL2NUM(mysql_insert_id(wrapper->client));
}
/* call-seq:
* client.affected_rows
*
* returns the number of rows changed, deleted, or inserted by the last statement
* if it was an UPDATE, DELETE, or INSERT.
*/
static VALUE rb_mysql_client_affected_rows(VALUE self) {
my_ulonglong retVal;
GET_CLIENT(self);
REQUIRE_CONNECTED(wrapper);
retVal = mysql_affected_rows(wrapper->client);
if (retVal == (my_ulonglong)-1) {
rb_raise_mysql2_error(wrapper);
}
return ULL2NUM(retVal);
}
/* call-seq:
* client.thread_id
*
* Returns the thread ID of the current connection.
*/
static VALUE rb_mysql_client_thread_id(VALUE self) {
unsigned long retVal;
GET_CLIENT(self);
REQUIRE_CONNECTED(wrapper);
retVal = mysql_thread_id(wrapper->client);
return ULL2NUM(retVal);
}
static void *nogvl_select_db(void *ptr) {
struct nogvl_select_db_args *args = ptr;
if (mysql_select_db(args->mysql, args->db) == 0)
return (void *)Qtrue;
else
return (void *)Qfalse;
}
/* call-seq:
* client.select_db(name)
*
* Causes the database specified by +name+ to become the default (current)
* database on the connection specified by mysql.
*/
static VALUE rb_mysql_client_select_db(VALUE self, VALUE db)
{
struct nogvl_select_db_args args;
GET_CLIENT(self);
REQUIRE_CONNECTED(wrapper);
args.mysql = wrapper->client;
args.db = StringValueCStr(db);
if (rb_thread_call_without_gvl(nogvl_select_db, &args, RUBY_UBF_IO, 0) == Qfalse)
rb_raise_mysql2_error(wrapper);
return db;
}
static void *nogvl_ping(void *ptr) {
MYSQL *client = ptr;
return (void *)(mysql_ping(client) == 0 ? Qtrue : Qfalse);
}