-
Notifications
You must be signed in to change notification settings - Fork 180
/
pg_connection.c
4342 lines (3821 loc) · 127 KB
/
pg_connection.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
/*
* pg_connection.c - PG::Connection class extension
* $Id$
*
*/
#include "pg.h"
/* Number of bytes that are reserved on the stack for query params. */
#define QUERYDATA_BUFFER_SIZE 4000
VALUE rb_cPGconn;
static ID s_id_encode;
static VALUE sym_type, sym_format, sym_value;
static VALUE sym_symbol, sym_string, sym_static_symbol;
static PQnoticeReceiver default_notice_receiver = NULL;
static PQnoticeProcessor default_notice_processor = NULL;
static VALUE pgconn_finish( VALUE );
static VALUE pgconn_set_default_encoding( VALUE self );
static void pgconn_set_internal_encoding_index( VALUE );
/*
* Global functions
*/
/*
* Fetch the PG::Connection object data pointer.
*/
t_pg_connection *
pg_get_connection( VALUE self )
{
t_pg_connection *this;
Data_Get_Struct( self, t_pg_connection, this);
return this;
}
/*
* Fetch the PG::Connection object data pointer and check it's
* PGconn data pointer for sanity.
*/
static t_pg_connection *
pg_get_connection_safe( VALUE self )
{
t_pg_connection *this;
Data_Get_Struct( self, t_pg_connection, this);
if ( !this->pgconn )
rb_raise( rb_eConnectionBad, "connection is closed" );
return this;
}
/*
* Fetch the PGconn data pointer and check it for sanity.
*
* Note: This function is used externally by the sequel_pg gem,
* so do changes carefully.
*
*/
PGconn *
pg_get_pgconn( VALUE self )
{
t_pg_connection *this;
Data_Get_Struct( self, t_pg_connection, this);
if ( !this->pgconn )
rb_raise( rb_eConnectionBad, "connection is closed" );
return this->pgconn;
}
/*
* Close the associated socket IO object if there is one.
*/
static void
pgconn_close_socket_io( VALUE self )
{
t_pg_connection *this = pg_get_connection( self );
VALUE socket_io = this->socket_io;
if ( RTEST(socket_io) ) {
#if defined(_WIN32)
if( rb_w32_unwrap_io_handle(this->ruby_sd) ){
rb_raise(rb_eConnectionBad, "Could not unwrap win32 socket handle");
}
#endif
rb_funcall( socket_io, rb_intern("close"), 0 );
}
this->socket_io = Qnil;
}
/*
* Create a Ruby Array of Hashes out of a PGconninfoOptions array.
*/
static VALUE
pgconn_make_conninfo_array( const PQconninfoOption *options )
{
VALUE ary = rb_ary_new();
VALUE hash;
int i = 0;
if (!options) return Qnil;
for(i = 0; options[i].keyword != NULL; i++) {
hash = rb_hash_new();
if(options[i].keyword)
rb_hash_aset(hash, ID2SYM(rb_intern("keyword")), rb_str_new2(options[i].keyword));
if(options[i].envvar)
rb_hash_aset(hash, ID2SYM(rb_intern("envvar")), rb_str_new2(options[i].envvar));
if(options[i].compiled)
rb_hash_aset(hash, ID2SYM(rb_intern("compiled")), rb_str_new2(options[i].compiled));
if(options[i].val)
rb_hash_aset(hash, ID2SYM(rb_intern("val")), rb_str_new2(options[i].val));
if(options[i].label)
rb_hash_aset(hash, ID2SYM(rb_intern("label")), rb_str_new2(options[i].label));
if(options[i].dispchar)
rb_hash_aset(hash, ID2SYM(rb_intern("dispchar")), rb_str_new2(options[i].dispchar));
rb_hash_aset(hash, ID2SYM(rb_intern("dispsize")), INT2NUM(options[i].dispsize));
rb_ary_push(ary, hash);
}
return ary;
}
static const char *pg_cstr_enc(VALUE str, int enc_idx){
const char *ptr = StringValueCStr(str);
if( ENCODING_GET(str) == enc_idx ){
return ptr;
} else {
str = rb_str_export_to_enc(str, rb_enc_from_index(enc_idx));
return StringValueCStr(str);
}
}
/*
* GC Mark function
*/
static void
pgconn_gc_mark( t_pg_connection *this )
{
rb_gc_mark( this->socket_io );
rb_gc_mark( this->notice_receiver );
rb_gc_mark( this->notice_processor );
rb_gc_mark( this->type_map_for_queries );
rb_gc_mark( this->type_map_for_results );
rb_gc_mark( this->trace_stream );
rb_gc_mark( this->encoder_for_put_copy_data );
rb_gc_mark( this->decoder_for_get_copy_data );
}
/*
* GC Free function
*/
static void
pgconn_gc_free( t_pg_connection *this )
{
#if defined(_WIN32)
if ( RTEST(this->socket_io) )
rb_w32_unwrap_io_handle( this->ruby_sd );
#endif
if (this->pgconn != NULL)
PQfinish( this->pgconn );
xfree(this);
}
/**************************************************************************
* Class Methods
**************************************************************************/
/*
* Document-method: allocate
*
* call-seq:
* PG::Connection.allocate -> conn
*/
static VALUE
pgconn_s_allocate( VALUE klass )
{
t_pg_connection *this;
VALUE self = Data_Make_Struct( klass, t_pg_connection, pgconn_gc_mark, pgconn_gc_free, this );
this->pgconn = NULL;
this->socket_io = Qnil;
this->notice_receiver = Qnil;
this->notice_processor = Qnil;
this->type_map_for_queries = pg_typemap_all_strings;
this->type_map_for_results = pg_typemap_all_strings;
this->encoder_for_put_copy_data = Qnil;
this->decoder_for_get_copy_data = Qnil;
this->trace_stream = Qnil;
return self;
}
/*
* Document-method: new
*
* call-seq:
* PG::Connection.new -> conn
* PG::Connection.new(connection_hash) -> conn
* PG::Connection.new(connection_string) -> conn
* PG::Connection.new(host, port, options, tty, dbname, user, password) -> conn
*
* Create a connection to the specified server.
*
* +connection_hash+ must be a ruby Hash with connection parameters.
* See the {list of valid parameters}[https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS] in the PostgreSQL documentation.
*
* There are two accepted formats for +connection_string+: plain <code>keyword = value</code> strings and URIs.
* See the documentation of {connection strings}[https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING].
*
* The positional parameter form has the same functionality except that the missing parameters will always take on default values. The parameters are:
* [+host+]
* server hostname
* [+port+]
* server port number
* [+options+]
* backend options
* [+tty+]
* (ignored in newer versions of PostgreSQL)
* [+dbname+]
* connecting database name
* [+user+]
* login user name
* [+password+]
* login password
*
* Examples:
*
* # Connect using all defaults
* PG::Connection.new
*
* # As a Hash
* PG::Connection.new( :dbname => 'test', :port => 5432 )
*
* # As a String
* PG::Connection.new( "dbname=test port=5432" )
*
* # As an Array
* PG::Connection.new( nil, 5432, nil, nil, 'test', nil, nil )
*
* If the Ruby default internal encoding is set (i.e., <code>Encoding.default_internal != nil</code>), the
* connection will have its +client_encoding+ set accordingly.
*
* Raises a PG::Error if the connection fails.
*/
static VALUE
pgconn_init(int argc, VALUE *argv, VALUE self)
{
t_pg_connection *this;
VALUE conninfo;
VALUE error;
this = pg_get_connection( self );
conninfo = rb_funcall2( rb_cPGconn, rb_intern("parse_connect_args"), argc, argv );
this->pgconn = gvl_PQconnectdb(StringValueCStr(conninfo));
if(this->pgconn == NULL)
rb_raise(rb_ePGerror, "PQconnectdb() unable to allocate structure");
if (PQstatus(this->pgconn) == CONNECTION_BAD) {
error = rb_exc_new2(rb_eConnectionBad, PQerrorMessage(this->pgconn));
rb_iv_set(error, "@connection", self);
rb_exc_raise(error);
}
pgconn_set_default_encoding( self );
if (rb_block_given_p()) {
return rb_ensure(rb_yield, self, pgconn_finish, self);
}
return self;
}
/*
* call-seq:
* PG::Connection.connect_start(connection_hash) -> conn
* PG::Connection.connect_start(connection_string) -> conn
* PG::Connection.connect_start(host, port, options, tty, dbname, login, password) -> conn
*
* This is an asynchronous version of PG::Connection.new.
*
* Use #connect_poll to poll the status of the connection.
*
* NOTE: this does *not* set the connection's +client_encoding+ for you if
* +Encoding.default_internal+ is set. To set it after the connection is established,
* call #internal_encoding=. You can also set it automatically by setting
* <code>ENV['PGCLIENTENCODING']</code>, or include the 'options' connection parameter.
*
* See also the 'sample' directory of this gem and the corresponding {libpq functions}[https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PQCONNECTSTARTPARAMS].
*
*/
static VALUE
pgconn_s_connect_start( int argc, VALUE *argv, VALUE klass )
{
VALUE rb_conn;
VALUE conninfo;
VALUE error;
t_pg_connection *this;
/*
* PG::Connection.connect_start must act as both alloc() and initialize()
* because it is not invoked by calling new().
*/
rb_conn = pgconn_s_allocate( klass );
this = pg_get_connection( rb_conn );
conninfo = rb_funcall2( klass, rb_intern("parse_connect_args"), argc, argv );
this->pgconn = gvl_PQconnectStart( StringValueCStr(conninfo) );
if( this->pgconn == NULL )
rb_raise(rb_ePGerror, "PQconnectStart() unable to allocate structure");
if ( PQstatus(this->pgconn) == CONNECTION_BAD ) {
error = rb_exc_new2(rb_eConnectionBad, PQerrorMessage(this->pgconn));
rb_iv_set(error, "@connection", rb_conn);
rb_exc_raise(error);
}
if ( rb_block_given_p() ) {
return rb_ensure( rb_yield, rb_conn, pgconn_finish, rb_conn );
}
return rb_conn;
}
/*
* call-seq:
* PG::Connection.ping(connection_hash) -> Integer
* PG::Connection.ping(connection_string) -> Integer
* PG::Connection.ping(host, port, options, tty, dbname, login, password) -> Integer
*
* Check server status.
*
* See PG::Connection.new for a description of the parameters.
*
* Returns one of:
* [+PQPING_OK+]
* server is accepting connections
* [+PQPING_REJECT+]
* server is alive but rejecting connections
* [+PQPING_NO_RESPONSE+]
* could not establish connection
* [+PQPING_NO_ATTEMPT+]
* connection not attempted (bad params)
*/
static VALUE
pgconn_s_ping( int argc, VALUE *argv, VALUE klass )
{
PGPing ping;
VALUE conninfo;
conninfo = rb_funcall2( klass, rb_intern("parse_connect_args"), argc, argv );
ping = PQping( StringValueCStr(conninfo) );
return INT2FIX((int)ping);
}
/*
* Document-method: PG::Connection.conndefaults
*
* call-seq:
* PG::Connection.conndefaults() -> Array
*
* Returns an array of hashes. Each hash has the keys:
* [+:keyword+]
* the name of the option
* [+:envvar+]
* the environment variable to fall back to
* [+:compiled+]
* the compiled in option as a secondary fallback
* [+:val+]
* the option's current value, or +nil+ if not known
* [+:label+]
* the label for the field
* [+:dispchar+]
* "" for normal, "D" for debug, and "*" for password
* [+:dispsize+]
* field size
*/
static VALUE
pgconn_s_conndefaults(VALUE self)
{
PQconninfoOption *options = PQconndefaults();
VALUE array = pgconn_make_conninfo_array( options );
PQconninfoFree(options);
UNUSED( self );
return array;
}
#ifdef HAVE_PQENCRYPTPASSWORDCONN
/*
* call-seq:
* conn.encrypt_password( password, username, algorithm=nil ) -> String
*
* This function is intended to be used by client applications that wish to send commands like <tt>ALTER USER joe PASSWORD 'pwd'</tt>.
* It is good practice not to send the original cleartext password in such a command, because it might be exposed in command logs, activity displays, and so on.
* Instead, use this function to convert the password to encrypted form before it is sent.
*
* The +password+ and +username+ arguments are the cleartext password, and the SQL name of the user it is for.
* +algorithm+ specifies the encryption algorithm to use to encrypt the password.
* Currently supported algorithms are +md5+ and +scram-sha-256+ (+on+ and +off+ are also accepted as aliases for +md5+, for compatibility with older server versions).
* Note that support for +scram-sha-256+ was introduced in PostgreSQL version 10, and will not work correctly with older server versions.
* If algorithm is omitted or +nil+, this function will query the server for the current value of the +password_encryption+ setting.
* That can block, and will fail if the current transaction is aborted, or if the connection is busy executing another query.
* If you wish to use the default algorithm for the server but want to avoid blocking, query +password_encryption+ yourself before calling #encrypt_password, and pass that value as the algorithm.
*
* Return value is the encrypted password.
* The caller can assume the string doesn't contain any special characters that would require escaping.
*
* Available since PostgreSQL-10.
* See also corresponding {libpq function}[https://www.postgresql.org/docs/current/libpq-misc.html#LIBPQ-PQENCRYPTPASSWORDCONN].
*/
static VALUE
pgconn_encrypt_password(int argc, VALUE *argv, VALUE self)
{
char *encrypted = NULL;
VALUE rval = Qnil;
VALUE password, username, algorithm;
PGconn *conn = pg_get_pgconn(self);
rb_scan_args( argc, argv, "21", &password, &username, &algorithm );
Check_Type(password, T_STRING);
Check_Type(username, T_STRING);
encrypted = gvl_PQencryptPasswordConn(conn, StringValueCStr(password), StringValueCStr(username), RTEST(algorithm) ? StringValueCStr(algorithm) : NULL);
if ( encrypted ) {
rval = rb_str_new2( encrypted );
PQfreemem( encrypted );
} else {
rb_raise(rb_ePGerror, "%s", PQerrorMessage(conn));
}
return rval;
}
#endif
/*
* call-seq:
* PG::Connection.encrypt_password( password, username ) -> String
*
* This is an older, deprecated version of #encrypt_password.
* The difference is that this function always uses +md5+ as the encryption algorithm.
*
*/
static VALUE
pgconn_s_encrypt_password(VALUE self, VALUE password, VALUE username)
{
char *encrypted = NULL;
VALUE rval = Qnil;
UNUSED( self );
Check_Type(password, T_STRING);
Check_Type(username, T_STRING);
encrypted = PQencryptPassword(StringValueCStr(password), StringValueCStr(username));
rval = rb_str_new2( encrypted );
PQfreemem( encrypted );
return rval;
}
/**************************************************************************
* PG::Connection INSTANCE METHODS
**************************************************************************/
/*
* call-seq:
* conn.connect_poll() -> Integer
*
* Returns one of:
* [+PGRES_POLLING_READING+]
* wait until the socket is ready to read
* [+PGRES_POLLING_WRITING+]
* wait until the socket is ready to write
* [+PGRES_POLLING_FAILED+]
* the asynchronous connection has failed
* [+PGRES_POLLING_OK+]
* the asynchronous connection is ready
*
* Example:
* conn = PG::Connection.connect_start("dbname=mydatabase")
* socket = conn.socket_io
* status = conn.connect_poll
* while(status != PG::PGRES_POLLING_OK) do
* # do some work while waiting for the connection to complete
* if(status == PG::PGRES_POLLING_READING)
* if(not select([socket], [], [], 10.0))
* raise "Asynchronous connection timed out!"
* end
* elsif(status == PG::PGRES_POLLING_WRITING)
* if(not select([], [socket], [], 10.0))
* raise "Asynchronous connection timed out!"
* end
* end
* status = conn.connect_poll
* end
* # now conn.status == CONNECTION_OK, and connection
* # is ready.
*/
static VALUE
pgconn_connect_poll(VALUE self)
{
PostgresPollingStatusType status;
status = gvl_PQconnectPoll(pg_get_pgconn(self));
return INT2FIX((int)status);
}
/*
* call-seq:
* conn.finish
*
* Closes the backend connection.
*/
static VALUE
pgconn_finish( VALUE self )
{
t_pg_connection *this = pg_get_connection_safe( self );
pgconn_close_socket_io( self );
PQfinish( this->pgconn );
this->pgconn = NULL;
return Qnil;
}
/*
* call-seq:
* conn.finished? -> boolean
*
* Returns +true+ if the backend connection has been closed.
*/
static VALUE
pgconn_finished_p( VALUE self )
{
t_pg_connection *this = pg_get_connection( self );
if ( this->pgconn ) return Qfalse;
return Qtrue;
}
/*
* call-seq:
* conn.reset()
*
* Resets the backend connection. This method closes the
* backend connection and tries to re-connect.
*/
static VALUE
pgconn_reset( VALUE self )
{
pgconn_close_socket_io( self );
gvl_PQreset( pg_get_pgconn(self) );
return self;
}
/*
* call-seq:
* conn.reset_start() -> nil
*
* Initiate a connection reset in a nonblocking manner.
* This will close the current connection and attempt to
* reconnect using the same connection parameters.
* Use #reset_poll to check the status of the
* connection reset.
*/
static VALUE
pgconn_reset_start(VALUE self)
{
pgconn_close_socket_io( self );
if(gvl_PQresetStart(pg_get_pgconn(self)) == 0)
rb_raise(rb_eUnableToSend, "reset has failed");
return Qnil;
}
/*
* call-seq:
* conn.reset_poll -> Integer
*
* Checks the status of a connection reset operation.
* See #connect_start and #connect_poll for
* usage information and return values.
*/
static VALUE
pgconn_reset_poll(VALUE self)
{
PostgresPollingStatusType status;
status = gvl_PQresetPoll(pg_get_pgconn(self));
return INT2FIX((int)status);
}
/*
* call-seq:
* conn.db()
*
* Returns the connected database name.
*/
static VALUE
pgconn_db(VALUE self)
{
char *db = PQdb(pg_get_pgconn(self));
if (!db) return Qnil;
return rb_str_new2(db);
}
/*
* call-seq:
* conn.user()
*
* Returns the authenticated user name.
*/
static VALUE
pgconn_user(VALUE self)
{
char *user = PQuser(pg_get_pgconn(self));
if (!user) return Qnil;
return rb_str_new2(user);
}
/*
* call-seq:
* conn.pass()
*
* Returns the authenticated password.
*/
static VALUE
pgconn_pass(VALUE self)
{
char *user = PQpass(pg_get_pgconn(self));
if (!user) return Qnil;
return rb_str_new2(user);
}
/*
* call-seq:
* conn.host()
*
* Returns the connected server name.
*/
static VALUE
pgconn_host(VALUE self)
{
char *host = PQhost(pg_get_pgconn(self));
if (!host) return Qnil;
return rb_str_new2(host);
}
/*
* call-seq:
* conn.port()
*
* Returns the connected server port number.
*/
static VALUE
pgconn_port(VALUE self)
{
char* port = PQport(pg_get_pgconn(self));
return INT2NUM(atol(port));
}
/*
* call-seq:
* conn.tty()
*
* Returns the connected pgtty. (Obsolete)
*/
static VALUE
pgconn_tty(VALUE self)
{
char *tty = PQtty(pg_get_pgconn(self));
if (!tty) return Qnil;
return rb_str_new2(tty);
}
/*
* call-seq:
* conn.options()
*
* Returns backend option string.
*/
static VALUE
pgconn_options(VALUE self)
{
char *options = PQoptions(pg_get_pgconn(self));
if (!options) return Qnil;
return rb_str_new2(options);
}
#ifdef HAVE_PQCONNINFO
/*
* call-seq:
* conn.conninfo -> hash
*
* Returns the connection options used by a live connection.
*
* Available since PostgreSQL-9.3
*/
static VALUE
pgconn_conninfo( VALUE self )
{
PGconn *conn = pg_get_pgconn(self);
PQconninfoOption *options = PQconninfo( conn );
VALUE array = pgconn_make_conninfo_array( options );
PQconninfoFree(options);
return array;
}
#endif
/*
* call-seq:
* conn.status()
*
* Returns status of connection : CONNECTION_OK or CONNECTION_BAD
*/
static VALUE
pgconn_status(VALUE self)
{
return INT2NUM(PQstatus(pg_get_pgconn(self)));
}
/*
* call-seq:
* conn.transaction_status()
*
* returns one of the following statuses:
* PQTRANS_IDLE = 0 (connection idle)
* PQTRANS_ACTIVE = 1 (command in progress)
* PQTRANS_INTRANS = 2 (idle, within transaction block)
* PQTRANS_INERROR = 3 (idle, within failed transaction)
* PQTRANS_UNKNOWN = 4 (cannot determine status)
*/
static VALUE
pgconn_transaction_status(VALUE self)
{
return INT2NUM(PQtransactionStatus(pg_get_pgconn(self)));
}
/*
* call-seq:
* conn.parameter_status( param_name ) -> String
*
* Returns the setting of parameter _param_name_, where
* _param_name_ is one of
* * +server_version+
* * +server_encoding+
* * +client_encoding+
* * +is_superuser+
* * +session_authorization+
* * +DateStyle+
* * +TimeZone+
* * +integer_datetimes+
* * +standard_conforming_strings+
*
* Returns nil if the value of the parameter is not known.
*/
static VALUE
pgconn_parameter_status(VALUE self, VALUE param_name)
{
const char *ret = PQparameterStatus(pg_get_pgconn(self), StringValueCStr(param_name));
if(ret == NULL)
return Qnil;
else
return rb_str_new2(ret);
}
/*
* call-seq:
* conn.protocol_version -> Integer
*
* The 3.0 protocol will normally be used when communicating with PostgreSQL 7.4
* or later servers; pre-7.4 servers support only protocol 2.0. (Protocol 1.0 is
* obsolete and not supported by libpq.)
*/
static VALUE
pgconn_protocol_version(VALUE self)
{
return INT2NUM(PQprotocolVersion(pg_get_pgconn(self)));
}
/*
* call-seq:
* conn.server_version -> Integer
*
* The number is formed by converting the major, minor, and revision
* numbers into two-decimal-digit numbers and appending them together.
* For example, version 7.4.2 will be returned as 70402, and version
* 8.1 will be returned as 80100 (leading zeroes are not shown). Zero
* is returned if the connection is bad.
*
*/
static VALUE
pgconn_server_version(VALUE self)
{
return INT2NUM(PQserverVersion(pg_get_pgconn(self)));
}
/*
* call-seq:
* conn.error_message -> String
*
* Returns the error message about connection.
*/
static VALUE
pgconn_error_message(VALUE self)
{
char *error = PQerrorMessage(pg_get_pgconn(self));
if (!error) return Qnil;
return rb_str_new2(error);
}
/*
* call-seq:
* conn.socket() -> Integer
*
* This method is deprecated. Please use the more portable method #socket_io .
*
* Returns the socket's file descriptor for this connection.
* <tt>IO.for_fd()</tt> can be used to build a proper IO object to the socket.
* If you do so, you will likely also want to set <tt>autoclose=false</tt>
* on it to prevent Ruby from closing the socket to PostgreSQL if it
* goes out of scope. Alternatively, you can use #socket_io, which
* creates an IO that's associated with the connection object itself,
* and so won't go out of scope until the connection does.
*
* *Note:* On Windows the file descriptor is not usable,
* since it can not be used to build a Ruby IO object.
*/
static VALUE
pgconn_socket(VALUE self)
{
int sd;
pg_deprecated(4, ("conn.socket is deprecated and should be replaced by conn.socket_io"));
if( (sd = PQsocket(pg_get_pgconn(self))) < 0)
rb_raise(rb_eConnectionBad, "PQsocket() can't get socket descriptor");
return INT2NUM(sd);
}
/*
* call-seq:
* conn.socket_io() -> IO
*
* Fetch a memorized IO object created from the Connection's underlying socket.
* This object can be used for IO.select to wait for events while running
* asynchronous API calls.
*
* Using this instead of #socket avoids the problem of the underlying connection
* being closed by Ruby when an IO created using <tt>IO.for_fd(conn.socket)</tt>
* goes out of scope. In contrast to #socket, it also works on Windows.
*/
static VALUE
pgconn_socket_io(VALUE self)
{
int sd;
int ruby_sd;
ID id_autoclose = rb_intern("autoclose=");
t_pg_connection *this = pg_get_connection_safe( self );
VALUE socket_io = this->socket_io;
if ( !RTEST(socket_io) ) {
if( (sd = PQsocket(this->pgconn)) < 0)
rb_raise(rb_eConnectionBad, "PQsocket() can't get socket descriptor");
#ifdef _WIN32
ruby_sd = rb_w32_wrap_io_handle((HANDLE)(intptr_t)sd, O_RDWR|O_BINARY|O_NOINHERIT);
this->ruby_sd = ruby_sd;
#else
ruby_sd = sd;
#endif
socket_io = rb_funcall( rb_cIO, rb_intern("for_fd"), 1, INT2NUM(ruby_sd) );
/* Disable autoclose feature */
rb_funcall( socket_io, id_autoclose, 1, Qfalse );
this->socket_io = socket_io;
}
return socket_io;
}
/*
* call-seq:
* conn.backend_pid() -> Integer
*
* Returns the process ID of the backend server
* process for this connection.
* Note that this is a PID on database server host.
*/
static VALUE
pgconn_backend_pid(VALUE self)
{
return INT2NUM(PQbackendPID(pg_get_pgconn(self)));
}
/*
* call-seq:
* conn.connection_needs_password() -> Boolean
*
* Returns +true+ if the authentication method required a
* password, but none was available. +false+ otherwise.
*/
static VALUE
pgconn_connection_needs_password(VALUE self)
{
return PQconnectionNeedsPassword(pg_get_pgconn(self)) ? Qtrue : Qfalse;
}
/*
* call-seq:
* conn.connection_used_password() -> Boolean
*
* Returns +true+ if the authentication method used
* a caller-supplied password, +false+ otherwise.
*/
static VALUE
pgconn_connection_used_password(VALUE self)
{
return PQconnectionUsedPassword(pg_get_pgconn(self)) ? Qtrue : Qfalse;
}
/* :TODO: get_ssl */
static VALUE pgconn_exec_params( int, VALUE *, VALUE );
/*
* call-seq:
* conn.sync_exec(sql) -> PG::Result
* conn.sync_exec(sql) {|pg_result| block }
*
* This function has the same behavior as #async_exec, but is implemented using the synchronous command processing API of libpq.
* It's not recommended to use explicit sync or async variants but #exec instead, unless you have a good reason to do so.
*
* Both #sync_exec and #async_exec release the GVL while waiting for server response, so that concurrent threads will get executed.
* However #async_exec has two advantages:
*
* 1. #async_exec can be aborted by signals (like Ctrl-C), while #exec blocks signal processing until the query is answered.
* 2. Ruby VM gets notified about IO blocked operations.
* It can therefore schedule things like garbage collection, while queries are running like in this proposal: https://bugs.ruby-lang.org/issues/14723
*/
static VALUE
pgconn_exec(int argc, VALUE *argv, VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
PGresult *result = NULL;
VALUE rb_pgresult;
/* If called with no or nil parameters, use PQexec for compatibility */
if ( argc == 1 || (argc >= 2 && argc <= 4 && NIL_P(argv[1]) )) {
VALUE query_str = argv[0];
result = gvl_PQexec(this->pgconn, pg_cstr_enc(query_str, this->enc_idx));
rb_pgresult = pg_new_result(result, self);
pg_result_check(rb_pgresult);
if (rb_block_given_p()) {
return rb_ensure(rb_yield, rb_pgresult, pg_result_clear, rb_pgresult);
}
return rb_pgresult;
}
pg_deprecated(0, ("forwarding exec to exec_params is deprecated"));
/* Otherwise, just call #exec_params instead for backward-compatibility */
return pgconn_exec_params( argc, argv, self );
}
struct linked_typecast_data {
struct linked_typecast_data *next;
char data[0];
};
/* This struct is allocated on the stack for all query execution functions. */