-
Notifications
You must be signed in to change notification settings - Fork 180
/
pg_connection.c
4677 lines (4059 loc) · 136 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 ID s_id_autoclose_set;
static VALUE sym_type, sym_format, sym_value;
static VALUE sym_symbol, sym_string, sym_static_symbol;
static VALUE pgconn_finish( VALUE );
static VALUE pgconn_set_default_encoding( VALUE self );
static VALUE pgconn_wait_for_flush( VALUE self );
static void pgconn_set_internal_encoding_index( VALUE );
static const rb_data_type_t pg_connection_type;
static VALUE pgconn_async_flush(VALUE self);
/*
* Global functions
*/
/*
* Convenience function to raise connection errors
*/
#ifdef __GNUC__
__attribute__((format(printf, 3, 4)))
#endif
NORETURN( static void
pg_raise_conn_error( VALUE klass, VALUE self, const char *format, ...))
{
VALUE msg, error;
va_list ap;
va_start(ap, format);
msg = rb_vsprintf(format, ap);
va_end(ap);
error = rb_exc_new_str(klass, msg);
rb_iv_set(error, "@connection", self);
rb_exc_raise(error);
}
/*
* Fetch the PG::Connection object data pointer.
*/
t_pg_connection *
pg_get_connection( VALUE self )
{
t_pg_connection *this;
TypedData_Get_Struct( self, t_pg_connection, &pg_connection_type, 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;
TypedData_Get_Struct( self, t_pg_connection, &pg_connection_type, this);
if ( !this->pgconn )
pg_raise_conn_error( rb_eConnectionBad, self, "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;
TypedData_Get_Struct( self, t_pg_connection, &pg_connection_type, this);
if ( !this->pgconn ){
pg_raise_conn_error( rb_eConnectionBad, self, "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) )
pg_raise_conn_error( rb_eConnectionBad, self, "Could not unwrap win32 socket handle");
#endif
rb_funcall( socket_io, rb_intern("close"), 0 );
}
RB_OBJ_WRITE(self, &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( void *_this )
{
t_pg_connection *this = (t_pg_connection *)_this;
rb_gc_mark_movable( this->socket_io );
rb_gc_mark_movable( this->notice_receiver );
rb_gc_mark_movable( this->notice_processor );
rb_gc_mark_movable( this->type_map_for_queries );
rb_gc_mark_movable( this->type_map_for_results );
rb_gc_mark_movable( this->trace_stream );
rb_gc_mark_movable( this->encoder_for_put_copy_data );
rb_gc_mark_movable( this->decoder_for_get_copy_data );
}
static void
pgconn_gc_compact( void *_this )
{
t_pg_connection *this = (t_pg_connection *)_this;
pg_gc_location( this->socket_io );
pg_gc_location( this->notice_receiver );
pg_gc_location( this->notice_processor );
pg_gc_location( this->type_map_for_queries );
pg_gc_location( this->type_map_for_results );
pg_gc_location( this->trace_stream );
pg_gc_location( this->encoder_for_put_copy_data );
pg_gc_location( this->decoder_for_get_copy_data );
}
/*
* GC Free function
*/
static void
pgconn_gc_free( void *_this )
{
t_pg_connection *this = (t_pg_connection *)_this;
#if defined(_WIN32)
if ( RTEST(this->socket_io) ) {
if( rb_w32_unwrap_io_handle(this->ruby_sd) ){
rb_warn("pg: Could not unwrap win32 socket handle by garbage collector");
}
}
#endif
if (this->pgconn != NULL)
PQfinish( this->pgconn );
xfree(this);
}
/*
* Object Size function
*/
static size_t
pgconn_memsize( const void *_this )
{
const t_pg_connection *this = (const t_pg_connection *)_this;
return sizeof(*this);
}
static const rb_data_type_t pg_connection_type = {
"PG::Connection",
{
pgconn_gc_mark,
pgconn_gc_free,
pgconn_memsize,
pg_compact_callback(pgconn_gc_compact),
},
0,
0,
RUBY_TYPED_WB_PROTECTED,
};
/**************************************************************************
* Class Methods
**************************************************************************/
/*
* Document-method: allocate
*
* call-seq:
* PG::Connection.allocate -> conn
*/
static VALUE
pgconn_s_allocate( VALUE klass )
{
t_pg_connection *this;
VALUE self = TypedData_Make_Struct( klass, t_pg_connection, &pg_connection_type, this );
this->pgconn = NULL;
RB_OBJ_WRITE(self, &this->socket_io, Qnil);
RB_OBJ_WRITE(self, &this->notice_receiver, Qnil);
RB_OBJ_WRITE(self, &this->notice_processor, Qnil);
RB_OBJ_WRITE(self, &this->type_map_for_queries, pg_typemap_all_strings);
RB_OBJ_WRITE(self, &this->type_map_for_results, pg_typemap_all_strings);
RB_OBJ_WRITE(self, &this->encoder_for_put_copy_data, Qnil);
RB_OBJ_WRITE(self, &this->decoder_for_get_copy_data, Qnil);
RB_OBJ_WRITE(self, &this->trace_stream, Qnil);
rb_ivar_set(self, rb_intern("@calls_to_put_copy_data"), INT2FIX(0));
return self;
}
static VALUE
pgconn_s_sync_connect(int argc, VALUE *argv, VALUE klass)
{
t_pg_connection *this;
VALUE conninfo;
VALUE self = pgconn_s_allocate( klass );
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 PGconn structure");
if (PQstatus(this->pgconn) == CONNECTION_BAD)
pg_raise_conn_error( rb_eConnectionBad, self, "%s", PQerrorMessage(this->pgconn));
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;
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 PGconn structure");
if ( PQstatus(this->pgconn) == CONNECTION_BAD )
pg_raise_conn_error( rb_eConnectionBad, rb_conn, "%s", PQerrorMessage(this->pgconn));
if ( rb_block_given_p() ) {
return rb_ensure( rb_yield, rb_conn, pgconn_finish, rb_conn );
}
return rb_conn;
}
static VALUE
pgconn_s_sync_ping( int argc, VALUE *argv, VALUE klass )
{
PGPing ping;
VALUE conninfo;
conninfo = rb_funcall2( klass, rb_intern("parse_connect_args"), argc, argv );
ping = gvl_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;
}
/*
* Document-method: PG::Connection.conninfo_parse
*
* call-seq:
* PG::Connection.conninfo_parse(conninfo_string) -> Array
*
* Returns parsed connection options from the provided connection string as an array of hashes.
* Each hash has the same keys as PG::Connection.conndefaults() .
* The values from the +conninfo_string+ are stored in the +:val+ key.
*/
static VALUE
pgconn_s_conninfo_parse(VALUE self, VALUE conninfo)
{
VALUE array;
char *errmsg = NULL;
PQconninfoOption *options = PQconninfoParse(StringValueCStr(conninfo), &errmsg);
if(errmsg){
VALUE error = rb_str_new_cstr(errmsg);
PQfreemem(errmsg);
rb_raise(rb_ePGerror, "%"PRIsVALUE, error);
}
array = pgconn_make_conninfo_array( options );
PQconninfoFree(options);
UNUSED( self );
return array;
}
#ifdef HAVE_PQENCRYPTPASSWORDCONN
static VALUE
pgconn_sync_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 {
pg_raise_conn_error( rb_ePGerror, self, "%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:
* require "io/wait"
*
* conn = PG::Connection.connect_start(dbname: 'mydatabase')
* 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)
* unless conn.socket_io.wait_readable(10.0)
* raise "Asynchronous connection timed out!"
* end
* elsif(status == PG::PGRES_POLLING_WRITING)
* unless conn.socket_io.wait_writable(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;
pgconn_close_socket_io(self);
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;
}
static VALUE
pgconn_sync_reset( VALUE self )
{
pgconn_close_socket_io( self );
gvl_PQreset( pg_get_pgconn(self) );
return self;
}
static VALUE
pgconn_reset_start2( VALUE self, VALUE conninfo )
{
t_pg_connection *this = pg_get_connection( self );
/* Close old connection */
pgconn_close_socket_io( self );
PQfinish( this->pgconn );
/* Start new connection */
this->pgconn = gvl_PQconnectStart( StringValueCStr(conninfo) );
if( this->pgconn == NULL )
rb_raise(rb_ePGerror, "PQconnectStart() unable to allocate PGconn structure");
if ( PQstatus(this->pgconn) == CONNECTION_BAD )
pg_raise_conn_error( rb_eConnectionBad, self, "%s", PQerrorMessage(this->pgconn));
return Qnil;
}
/*
* 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)
pg_raise_conn_error( rb_eUnableToSend, self, "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;
pgconn_close_socket_io(self);
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 server host name of the active connection.
* This can be a host name, an IP address, or a directory path if the connection is via Unix socket.
* (The path case can be distinguished because it will always be an absolute path, beginning with +/+ .)
*
* If the connection parameters specified both host and hostaddr, then +host+ will return the host information.
* If only hostaddr was specified, then that is returned.
* If multiple hosts were specified in the connection parameters, +host+ returns the host actually connected to.
*
* If there is an error producing the host information (perhaps if the connection has not been fully established or there was an error), it returns an empty string.
*
* If multiple hosts were specified in the connection parameters, it is not possible to rely on the result of +host+ until the connection is established.
* The status of the connection can be checked using the function Connection#status .
*/
static VALUE
pgconn_host(VALUE self)
{
char *host = PQhost(pg_get_pgconn(self));
if (!host) return Qnil;
return rb_str_new2(host);
}
/* PQhostaddr() appeared in PostgreSQL-12 together with PQresultMemorySize() */
#if defined(HAVE_PQRESULTMEMORYSIZE)
/*
* call-seq:
* conn.hostaddr()
*
* Returns the server IP address of the active connection.
* This can be the address that a host name resolved to, or an IP address provided through the hostaddr parameter.
* If there is an error producing the host information (perhaps if the connection has not been fully established or there was an error), it returns an empty string.
*
*/
static VALUE
pgconn_hostaddr(VALUE self)
{
char *host = PQhostaddr(pg_get_pgconn(self));
if (!host) return Qnil;
return rb_str_new2(host);
}
#endif
/*
* call-seq:
* conn.port()
*
* Returns the connected server port number.
*/
static VALUE
pgconn_port(VALUE self)
{
char* port = PQport(pg_get_pgconn(self));
if (!port || port[0] == '\0')
return INT2NUM(DEF_PGPORT);
else
return INT2NUM(atoi(port));
}
/*
* call-seq:
* conn.tty()
*
* Obsolete function.
*/
static VALUE
pgconn_tty(VALUE self)
{
return rb_str_new2("");
}
/*
* 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);
}
/*
* 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;
}
/*
* call-seq:
* conn.status()
*
* Returns the status of the connection, which is one:
* PG::Constants::CONNECTION_OK
* PG::Constants::CONNECTION_BAD
*
* ... and other constants of kind PG::Constants::CONNECTION_*
*
* This method returns the status of the last command from memory.
* It doesn't do any socket access hence is not suitable to test the connectivity.
* See check_socket for a way to verify the socket state.
*
* Example:
* PG.constants.grep(/CONNECTION_/).find{|c| PG.const_get(c) == conn.status} # => :CONNECTION_OK
*/
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 most recently generated by an operation on the connection.
*
* Nearly all libpq functions will set a message for conn.error_message if they fail.
* Note that by libpq convention, a nonempty error_message result can consist of multiple lines, and will include a trailing newline.
*/
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)
pg_raise_conn_error( rb_eConnectionBad, self, "PQsocket() can't get socket descriptor");
return INT2NUM(sd);
}
/*
* call-seq:
* conn.socket_io() -> IO
*
* Fetch an IO object created from the Connection's underlying socket.
* This object can be used per <tt>socket_io.wait_readable</tt>, <tt>socket_io.wait_writable</tt> or for <tt>IO.select</tt> to wait for events while running asynchronous API calls.
* <tt>IO#wait_*able</tt> is is <tt>Fiber.scheduler</tt> compatible in contrast to <tt>IO.select</tt>.
*
* The IO object can change while the connection is established, but is memorized afterwards.
* So be sure not to cache the IO object, but repeat calling <tt>conn.socket_io</tt> instead.
*
* Using this method also works on Windows in contrast to using #socket .
* It also 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.
*/
static VALUE
pgconn_socket_io(VALUE self)
{
int sd;
int ruby_sd;
t_pg_connection *this = pg_get_connection_safe( self );
VALUE cSocket;
VALUE socket_io = this->socket_io;
if ( !RTEST(socket_io) ) {
if( (sd = PQsocket(this->pgconn)) < 0){
pg_raise_conn_error( rb_eConnectionBad, self, "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);
if( ruby_sd == -1 )
pg_raise_conn_error( rb_eConnectionBad, self, "Could not wrap win32 socket handle");
this->ruby_sd = ruby_sd;
#else
ruby_sd = sd;
#endif
cSocket = rb_const_get(rb_cObject, rb_intern("BasicSocket"));
socket_io = rb_funcall( cSocket, rb_intern("for_fd"), 1, INT2NUM(ruby_sd));
/* Disable autoclose feature */
rb_funcall( socket_io, s_id_autoclose_set, 1, Qfalse );
RB_OBJ_WRITE(self, &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)));
}
typedef struct
{
struct sockaddr_storage addr;
socklen_t salen;
} SockAddr;
/* Copy of struct pg_cancel from libpq-int.h
*
* See https://github.com/postgres/postgres/blame/master/src/interfaces/libpq/libpq-int.h#L577-L586
*/
struct pg_cancel
{
SockAddr raddr; /* Remote address */
int be_pid; /* PID of backend --- needed for cancels */
int be_key; /* key of backend --- needed for cancels */