pg 1.1.4

Sign up to get free protection for your applications and to get access to all the features.
Files changed (77) hide show
  1. checksums.yaml +7 -0
  2. checksums.yaml.gz.sig +3 -0
  3. data.tar.gz.sig +0 -0
  4. data/.gemtest +0 -0
  5. data/BSDL +22 -0
  6. data/ChangeLog +6595 -0
  7. data/Contributors.rdoc +46 -0
  8. data/History.rdoc +492 -0
  9. data/LICENSE +56 -0
  10. data/Manifest.txt +72 -0
  11. data/POSTGRES +23 -0
  12. data/README-OS_X.rdoc +68 -0
  13. data/README-Windows.rdoc +56 -0
  14. data/README.ja.rdoc +14 -0
  15. data/README.rdoc +178 -0
  16. data/Rakefile +215 -0
  17. data/Rakefile.cross +298 -0
  18. data/ext/errorcodes.def +968 -0
  19. data/ext/errorcodes.rb +45 -0
  20. data/ext/errorcodes.txt +478 -0
  21. data/ext/extconf.rb +94 -0
  22. data/ext/gvl_wrappers.c +17 -0
  23. data/ext/gvl_wrappers.h +241 -0
  24. data/ext/pg.c +640 -0
  25. data/ext/pg.h +365 -0
  26. data/ext/pg_binary_decoder.c +229 -0
  27. data/ext/pg_binary_encoder.c +162 -0
  28. data/ext/pg_coder.c +549 -0
  29. data/ext/pg_connection.c +4252 -0
  30. data/ext/pg_copy_coder.c +596 -0
  31. data/ext/pg_errors.c +95 -0
  32. data/ext/pg_result.c +1501 -0
  33. data/ext/pg_text_decoder.c +981 -0
  34. data/ext/pg_text_encoder.c +682 -0
  35. data/ext/pg_tuple.c +541 -0
  36. data/ext/pg_type_map.c +166 -0
  37. data/ext/pg_type_map_all_strings.c +116 -0
  38. data/ext/pg_type_map_by_class.c +239 -0
  39. data/ext/pg_type_map_by_column.c +312 -0
  40. data/ext/pg_type_map_by_mri_type.c +284 -0
  41. data/ext/pg_type_map_by_oid.c +355 -0
  42. data/ext/pg_type_map_in_ruby.c +299 -0
  43. data/ext/util.c +149 -0
  44. data/ext/util.h +65 -0
  45. data/ext/vc/pg.sln +26 -0
  46. data/ext/vc/pg_18/pg.vcproj +216 -0
  47. data/ext/vc/pg_19/pg_19.vcproj +209 -0
  48. data/lib/pg.rb +74 -0
  49. data/lib/pg/basic_type_mapping.rb +459 -0
  50. data/lib/pg/binary_decoder.rb +22 -0
  51. data/lib/pg/coder.rb +83 -0
  52. data/lib/pg/connection.rb +291 -0
  53. data/lib/pg/constants.rb +11 -0
  54. data/lib/pg/exceptions.rb +11 -0
  55. data/lib/pg/result.rb +31 -0
  56. data/lib/pg/text_decoder.rb +47 -0
  57. data/lib/pg/text_encoder.rb +69 -0
  58. data/lib/pg/tuple.rb +30 -0
  59. data/lib/pg/type_map_by_column.rb +15 -0
  60. data/spec/data/expected_trace.out +26 -0
  61. data/spec/data/random_binary_data +0 -0
  62. data/spec/helpers.rb +380 -0
  63. data/spec/pg/basic_type_mapping_spec.rb +508 -0
  64. data/spec/pg/connection_spec.rb +1872 -0
  65. data/spec/pg/connection_sync_spec.rb +41 -0
  66. data/spec/pg/result_spec.rb +491 -0
  67. data/spec/pg/tuple_spec.rb +280 -0
  68. data/spec/pg/type_map_by_class_spec.rb +138 -0
  69. data/spec/pg/type_map_by_column_spec.rb +222 -0
  70. data/spec/pg/type_map_by_mri_type_spec.rb +136 -0
  71. data/spec/pg/type_map_by_oid_spec.rb +149 -0
  72. data/spec/pg/type_map_in_ruby_spec.rb +164 -0
  73. data/spec/pg/type_map_spec.rb +22 -0
  74. data/spec/pg/type_spec.rb +949 -0
  75. data/spec/pg_spec.rb +50 -0
  76. metadata +322 -0
  77. metadata.gz.sig +0 -0
@@ -0,0 +1,4252 @@
1
+ /*
2
+ * pg_connection.c - PG::Connection class extension
3
+ * $Id$
4
+ *
5
+ */
6
+
7
+ #include "pg.h"
8
+
9
+ /* Number of bytes that are reserved on the stack for query params. */
10
+ #define QUERYDATA_BUFFER_SIZE 4000
11
+
12
+
13
+ VALUE rb_cPGconn;
14
+ static ID s_id_encode;
15
+ static VALUE sym_type, sym_format, sym_value;
16
+
17
+ static PQnoticeReceiver default_notice_receiver = NULL;
18
+ static PQnoticeProcessor default_notice_processor = NULL;
19
+
20
+ static VALUE pgconn_finish( VALUE );
21
+ static VALUE pgconn_set_default_encoding( VALUE self );
22
+ void pgconn_set_internal_encoding_index( VALUE );
23
+
24
+ /*
25
+ * Global functions
26
+ */
27
+
28
+ /*
29
+ * Fetch the PG::Connection object data pointer.
30
+ */
31
+ t_pg_connection *
32
+ pg_get_connection( VALUE self )
33
+ {
34
+ t_pg_connection *this;
35
+ Data_Get_Struct( self, t_pg_connection, this);
36
+
37
+ return this;
38
+ }
39
+
40
+ /*
41
+ * Fetch the PG::Connection object data pointer and check it's
42
+ * PGconn data pointer for sanity.
43
+ */
44
+ static t_pg_connection *
45
+ pg_get_connection_safe( VALUE self )
46
+ {
47
+ t_pg_connection *this;
48
+ Data_Get_Struct( self, t_pg_connection, this);
49
+
50
+ if ( !this->pgconn )
51
+ rb_raise( rb_eConnectionBad, "connection is closed" );
52
+
53
+ return this;
54
+ }
55
+
56
+ /*
57
+ * Fetch the PGconn data pointer and check it for sanity.
58
+ *
59
+ * Note: This function is used externally by the sequel_pg gem,
60
+ * so do changes carefully.
61
+ *
62
+ */
63
+ PGconn *
64
+ pg_get_pgconn( VALUE self )
65
+ {
66
+ t_pg_connection *this;
67
+ Data_Get_Struct( self, t_pg_connection, this);
68
+
69
+ if ( !this->pgconn )
70
+ rb_raise( rb_eConnectionBad, "connection is closed" );
71
+
72
+ return this->pgconn;
73
+ }
74
+
75
+
76
+
77
+ /*
78
+ * Close the associated socket IO object if there is one.
79
+ */
80
+ static void
81
+ pgconn_close_socket_io( VALUE self )
82
+ {
83
+ t_pg_connection *this = pg_get_connection( self );
84
+ VALUE socket_io = this->socket_io;
85
+
86
+ if ( RTEST(socket_io) ) {
87
+ #if defined(_WIN32)
88
+ if( rb_w32_unwrap_io_handle(this->ruby_sd) ){
89
+ rb_raise(rb_eConnectionBad, "Could not unwrap win32 socket handle");
90
+ }
91
+ #endif
92
+ rb_funcall( socket_io, rb_intern("close"), 0 );
93
+ }
94
+
95
+ this->socket_io = Qnil;
96
+ }
97
+
98
+
99
+ /*
100
+ * Create a Ruby Array of Hashes out of a PGconninfoOptions array.
101
+ */
102
+ static VALUE
103
+ pgconn_make_conninfo_array( const PQconninfoOption *options )
104
+ {
105
+ VALUE ary = rb_ary_new();
106
+ VALUE hash;
107
+ int i = 0;
108
+
109
+ if (!options) return Qnil;
110
+
111
+ for(i = 0; options[i].keyword != NULL; i++) {
112
+ hash = rb_hash_new();
113
+ if(options[i].keyword)
114
+ rb_hash_aset(hash, ID2SYM(rb_intern("keyword")), rb_str_new2(options[i].keyword));
115
+ if(options[i].envvar)
116
+ rb_hash_aset(hash, ID2SYM(rb_intern("envvar")), rb_str_new2(options[i].envvar));
117
+ if(options[i].compiled)
118
+ rb_hash_aset(hash, ID2SYM(rb_intern("compiled")), rb_str_new2(options[i].compiled));
119
+ if(options[i].val)
120
+ rb_hash_aset(hash, ID2SYM(rb_intern("val")), rb_str_new2(options[i].val));
121
+ if(options[i].label)
122
+ rb_hash_aset(hash, ID2SYM(rb_intern("label")), rb_str_new2(options[i].label));
123
+ if(options[i].dispchar)
124
+ rb_hash_aset(hash, ID2SYM(rb_intern("dispchar")), rb_str_new2(options[i].dispchar));
125
+ rb_hash_aset(hash, ID2SYM(rb_intern("dispsize")), INT2NUM(options[i].dispsize));
126
+ rb_ary_push(ary, hash);
127
+ }
128
+
129
+ return ary;
130
+ }
131
+
132
+ static const char *pg_cstr_enc(VALUE str, int enc_idx){
133
+ const char *ptr = StringValueCStr(str);
134
+ if( ENCODING_GET(str) == enc_idx ){
135
+ return ptr;
136
+ } else {
137
+ str = rb_str_export_to_enc(str, rb_enc_from_index(enc_idx));
138
+ return StringValueCStr(str);
139
+ }
140
+ }
141
+
142
+
143
+ /*
144
+ * GC Mark function
145
+ */
146
+ static void
147
+ pgconn_gc_mark( t_pg_connection *this )
148
+ {
149
+ rb_gc_mark( this->socket_io );
150
+ rb_gc_mark( this->notice_receiver );
151
+ rb_gc_mark( this->notice_processor );
152
+ rb_gc_mark( this->type_map_for_queries );
153
+ rb_gc_mark( this->type_map_for_results );
154
+ rb_gc_mark( this->trace_stream );
155
+ rb_gc_mark( this->external_encoding );
156
+ rb_gc_mark( this->encoder_for_put_copy_data );
157
+ rb_gc_mark( this->decoder_for_get_copy_data );
158
+ }
159
+
160
+
161
+ /*
162
+ * GC Free function
163
+ */
164
+ static void
165
+ pgconn_gc_free( t_pg_connection *this )
166
+ {
167
+ #if defined(_WIN32)
168
+ if ( RTEST(this->socket_io) )
169
+ rb_w32_unwrap_io_handle( this->ruby_sd );
170
+ #endif
171
+ if (this->pgconn != NULL)
172
+ PQfinish( this->pgconn );
173
+
174
+ xfree(this);
175
+ }
176
+
177
+
178
+ /**************************************************************************
179
+ * Class Methods
180
+ **************************************************************************/
181
+
182
+ /*
183
+ * Document-method: allocate
184
+ *
185
+ * call-seq:
186
+ * PG::Connection.allocate -> conn
187
+ */
188
+ static VALUE
189
+ pgconn_s_allocate( VALUE klass )
190
+ {
191
+ t_pg_connection *this;
192
+ VALUE self = Data_Make_Struct( klass, t_pg_connection, pgconn_gc_mark, pgconn_gc_free, this );
193
+
194
+ this->pgconn = NULL;
195
+ this->socket_io = Qnil;
196
+ this->notice_receiver = Qnil;
197
+ this->notice_processor = Qnil;
198
+ this->type_map_for_queries = pg_typemap_all_strings;
199
+ this->type_map_for_results = pg_typemap_all_strings;
200
+ this->encoder_for_put_copy_data = Qnil;
201
+ this->decoder_for_get_copy_data = Qnil;
202
+ this->trace_stream = Qnil;
203
+ this->external_encoding = Qnil;
204
+ this->guess_result_memsize = 1;
205
+
206
+ return self;
207
+ }
208
+
209
+
210
+ /*
211
+ * Document-method: new
212
+ *
213
+ * call-seq:
214
+ * PG::Connection.new -> conn
215
+ * PG::Connection.new(connection_hash) -> conn
216
+ * PG::Connection.new(connection_string) -> conn
217
+ * PG::Connection.new(host, port, options, tty, dbname, user, password) -> conn
218
+ *
219
+ * Create a connection to the specified server.
220
+ *
221
+ * [+host+]
222
+ * server hostname
223
+ * [+hostaddr+]
224
+ * server address (avoids hostname lookup, overrides +host+)
225
+ * [+port+]
226
+ * server port number
227
+ * [+dbname+]
228
+ * connecting database name
229
+ * [+user+]
230
+ * login user name
231
+ * [+password+]
232
+ * login password
233
+ * [+connect_timeout+]
234
+ * maximum time to wait for connection to succeed
235
+ * [+options+]
236
+ * backend options
237
+ * [+tty+]
238
+ * (ignored in newer versions of PostgreSQL)
239
+ * [+sslmode+]
240
+ * (disable|allow|prefer|require)
241
+ * [+krbsrvname+]
242
+ * kerberos service name
243
+ * [+gsslib+]
244
+ * GSS library to use for GSSAPI authentication
245
+ * [+service+]
246
+ * service name to use for additional parameters
247
+ *
248
+ * Examples:
249
+ *
250
+ * # Connect using all defaults
251
+ * PG::Connection.new
252
+ *
253
+ * # As a Hash
254
+ * PG::Connection.new( :dbname => 'test', :port => 5432 )
255
+ *
256
+ * # As a String
257
+ * PG::Connection.new( "dbname=test port=5432" )
258
+ *
259
+ * # As an Array
260
+ * PG::Connection.new( nil, 5432, nil, nil, 'test', nil, nil )
261
+ *
262
+ * If the Ruby default internal encoding is set (i.e., Encoding.default_internal != nil), the
263
+ * connection will have its +client_encoding+ set accordingly.
264
+ *
265
+ * Raises a PG::Error if the connection fails.
266
+ */
267
+ static VALUE
268
+ pgconn_init(int argc, VALUE *argv, VALUE self)
269
+ {
270
+ t_pg_connection *this;
271
+ VALUE conninfo;
272
+ VALUE error;
273
+
274
+ this = pg_get_connection( self );
275
+ conninfo = rb_funcall2( rb_cPGconn, rb_intern("parse_connect_args"), argc, argv );
276
+ this->pgconn = gvl_PQconnectdb(StringValueCStr(conninfo));
277
+
278
+ if(this->pgconn == NULL)
279
+ rb_raise(rb_ePGerror, "PQconnectdb() unable to allocate structure");
280
+
281
+ if (PQstatus(this->pgconn) == CONNECTION_BAD) {
282
+ error = rb_exc_new2(rb_eConnectionBad, PQerrorMessage(this->pgconn));
283
+ rb_iv_set(error, "@connection", self);
284
+ rb_exc_raise(error);
285
+ }
286
+
287
+ pgconn_set_default_encoding( self );
288
+
289
+ if (rb_block_given_p()) {
290
+ return rb_ensure(rb_yield, self, pgconn_finish, self);
291
+ }
292
+ return self;
293
+ }
294
+
295
+ /*
296
+ * call-seq:
297
+ * PG::Connection.connect_start(connection_hash) -> conn
298
+ * PG::Connection.connect_start(connection_string) -> conn
299
+ * PG::Connection.connect_start(host, port, options, tty, dbname, login, password) -> conn
300
+ *
301
+ * This is an asynchronous version of PG::Connection.connect().
302
+ *
303
+ * Use #connect_poll to poll the status of the connection.
304
+ *
305
+ * NOTE: this does *not* set the connection's +client_encoding+ for you if
306
+ * Encoding.default_internal is set. To set it after the connection is established,
307
+ * call #internal_encoding=. You can also set it automatically by setting
308
+ * ENV['PGCLIENTENCODING'], or include the 'options' connection parameter.
309
+ *
310
+ */
311
+ static VALUE
312
+ pgconn_s_connect_start( int argc, VALUE *argv, VALUE klass )
313
+ {
314
+ VALUE rb_conn;
315
+ VALUE conninfo;
316
+ VALUE error;
317
+ t_pg_connection *this;
318
+
319
+ /*
320
+ * PG::Connection.connect_start must act as both alloc() and initialize()
321
+ * because it is not invoked by calling new().
322
+ */
323
+ rb_conn = pgconn_s_allocate( klass );
324
+ this = pg_get_connection( rb_conn );
325
+ conninfo = rb_funcall2( klass, rb_intern("parse_connect_args"), argc, argv );
326
+ this->pgconn = gvl_PQconnectStart( StringValueCStr(conninfo) );
327
+
328
+ if( this->pgconn == NULL )
329
+ rb_raise(rb_ePGerror, "PQconnectStart() unable to allocate structure");
330
+
331
+ if ( PQstatus(this->pgconn) == CONNECTION_BAD ) {
332
+ error = rb_exc_new2(rb_eConnectionBad, PQerrorMessage(this->pgconn));
333
+ rb_iv_set(error, "@connection", rb_conn);
334
+ rb_exc_raise(error);
335
+ }
336
+
337
+ if ( rb_block_given_p() ) {
338
+ return rb_ensure( rb_yield, rb_conn, pgconn_finish, rb_conn );
339
+ }
340
+ return rb_conn;
341
+ }
342
+
343
+ /*
344
+ * call-seq:
345
+ * PG::Connection.ping(connection_hash) -> Integer
346
+ * PG::Connection.ping(connection_string) -> Integer
347
+ * PG::Connection.ping(host, port, options, tty, dbname, login, password) -> Integer
348
+ *
349
+ * Check server status.
350
+ *
351
+ * Returns one of:
352
+ * [+PQPING_OK+]
353
+ * server is accepting connections
354
+ * [+PQPING_REJECT+]
355
+ * server is alive but rejecting connections
356
+ * [+PQPING_NO_RESPONSE+]
357
+ * could not establish connection
358
+ * [+PQPING_NO_ATTEMPT+]
359
+ * connection not attempted (bad params)
360
+ *
361
+ * Available since PostgreSQL-9.1
362
+ */
363
+ static VALUE
364
+ pgconn_s_ping( int argc, VALUE *argv, VALUE klass )
365
+ {
366
+ PGPing ping;
367
+ VALUE conninfo;
368
+
369
+ conninfo = rb_funcall2( klass, rb_intern("parse_connect_args"), argc, argv );
370
+ ping = PQping( StringValueCStr(conninfo) );
371
+
372
+ return INT2FIX((int)ping);
373
+ }
374
+
375
+
376
+ /*
377
+ * Document-method: PG::Connection.conndefaults
378
+ *
379
+ * call-seq:
380
+ * PG::Connection.conndefaults() -> Array
381
+ *
382
+ * Returns an array of hashes. Each hash has the keys:
383
+ * [+:keyword+]
384
+ * the name of the option
385
+ * [+:envvar+]
386
+ * the environment variable to fall back to
387
+ * [+:compiled+]
388
+ * the compiled in option as a secondary fallback
389
+ * [+:val+]
390
+ * the option's current value, or +nil+ if not known
391
+ * [+:label+]
392
+ * the label for the field
393
+ * [+:dispchar+]
394
+ * "" for normal, "D" for debug, and "*" for password
395
+ * [+:dispsize+]
396
+ * field size
397
+ */
398
+ static VALUE
399
+ pgconn_s_conndefaults(VALUE self)
400
+ {
401
+ PQconninfoOption *options = PQconndefaults();
402
+ VALUE array = pgconn_make_conninfo_array( options );
403
+
404
+ PQconninfoFree(options);
405
+
406
+ UNUSED( self );
407
+
408
+ return array;
409
+ }
410
+
411
+
412
+ #ifdef HAVE_PQENCRYPTPASSWORDCONN
413
+ /*
414
+ * call-seq:
415
+ * conn.encrypt_password( password, username, algorithm=nil ) -> String
416
+ *
417
+ * This function is intended to be used by client applications that wish to send commands like <tt>ALTER USER joe PASSWORD 'pwd'</tt>.
418
+ * 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.
419
+ * Instead, use this function to convert the password to encrypted form before it is sent.
420
+ *
421
+ * The +password+ and +username+ arguments are the cleartext password, and the SQL name of the user it is for.
422
+ * +algorithm+ specifies the encryption algorithm to use to encrypt the password.
423
+ * 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).
424
+ * Note that support for +scram-sha-256+ was introduced in PostgreSQL version 10, and will not work correctly with older server versions.
425
+ * If algorithm is omitted or +nil+, this function will query the server for the current value of the +password_encryption+ setting.
426
+ * That can block, and will fail if the current transaction is aborted, or if the connection is busy executing another query.
427
+ * 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.
428
+ *
429
+ * Return value is the encrypted password.
430
+ * The caller can assume the string doesn't contain any special characters that would require escaping.
431
+ *
432
+ * Available since PostgreSQL-10
433
+ */
434
+ static VALUE
435
+ pgconn_encrypt_password(int argc, VALUE *argv, VALUE self)
436
+ {
437
+ char *encrypted = NULL;
438
+ VALUE rval = Qnil;
439
+ VALUE password, username, algorithm;
440
+ PGconn *conn = pg_get_pgconn(self);
441
+
442
+ rb_scan_args( argc, argv, "21", &password, &username, &algorithm );
443
+
444
+ Check_Type(password, T_STRING);
445
+ Check_Type(username, T_STRING);
446
+
447
+ encrypted = gvl_PQencryptPasswordConn(conn, StringValueCStr(password), StringValueCStr(username), RTEST(algorithm) ? StringValueCStr(algorithm) : NULL);
448
+ if ( encrypted ) {
449
+ rval = rb_str_new2( encrypted );
450
+ PQfreemem( encrypted );
451
+
452
+ OBJ_INFECT( rval, password );
453
+ OBJ_INFECT( rval, username );
454
+ OBJ_INFECT( rval, algorithm );
455
+ } else {
456
+ rb_raise(rb_ePGerror, "%s", PQerrorMessage(conn));
457
+ }
458
+
459
+ return rval;
460
+ }
461
+ #endif
462
+
463
+
464
+ /*
465
+ * call-seq:
466
+ * PG::Connection.encrypt_password( password, username ) -> String
467
+ *
468
+ * This is an older, deprecated version of #encrypt_password.
469
+ * The difference is that this function always uses +md5+ as the encryption algorithm.
470
+ *
471
+ */
472
+ static VALUE
473
+ pgconn_s_encrypt_password(VALUE self, VALUE password, VALUE username)
474
+ {
475
+ char *encrypted = NULL;
476
+ VALUE rval = Qnil;
477
+
478
+ UNUSED( self );
479
+
480
+ Check_Type(password, T_STRING);
481
+ Check_Type(username, T_STRING);
482
+
483
+ encrypted = PQencryptPassword(StringValueCStr(password), StringValueCStr(username));
484
+ rval = rb_str_new2( encrypted );
485
+ PQfreemem( encrypted );
486
+
487
+ OBJ_INFECT( rval, password );
488
+ OBJ_INFECT( rval, username );
489
+
490
+ return rval;
491
+ }
492
+
493
+
494
+ /**************************************************************************
495
+ * PG::Connection INSTANCE METHODS
496
+ **************************************************************************/
497
+
498
+ /*
499
+ * call-seq:
500
+ * conn.connect_poll() -> Integer
501
+ *
502
+ * Returns one of:
503
+ * [+PGRES_POLLING_READING+]
504
+ * wait until the socket is ready to read
505
+ * [+PGRES_POLLING_WRITING+]
506
+ * wait until the socket is ready to write
507
+ * [+PGRES_POLLING_FAILED+]
508
+ * the asynchronous connection has failed
509
+ * [+PGRES_POLLING_OK+]
510
+ * the asynchronous connection is ready
511
+ *
512
+ * Example:
513
+ * conn = PG::Connection.connect_start("dbname=mydatabase")
514
+ * socket = conn.socket_io
515
+ * status = conn.connect_poll
516
+ * while(status != PG::PGRES_POLLING_OK) do
517
+ * # do some work while waiting for the connection to complete
518
+ * if(status == PG::PGRES_POLLING_READING)
519
+ * if(not select([socket], [], [], 10.0))
520
+ * raise "Asynchronous connection timed out!"
521
+ * end
522
+ * elsif(status == PG::PGRES_POLLING_WRITING)
523
+ * if(not select([], [socket], [], 10.0))
524
+ * raise "Asynchronous connection timed out!"
525
+ * end
526
+ * end
527
+ * status = conn.connect_poll
528
+ * end
529
+ * # now conn.status == CONNECTION_OK, and connection
530
+ * # is ready.
531
+ */
532
+ static VALUE
533
+ pgconn_connect_poll(VALUE self)
534
+ {
535
+ PostgresPollingStatusType status;
536
+ status = gvl_PQconnectPoll(pg_get_pgconn(self));
537
+ return INT2FIX((int)status);
538
+ }
539
+
540
+ /*
541
+ * call-seq:
542
+ * conn.finish
543
+ *
544
+ * Closes the backend connection.
545
+ */
546
+ static VALUE
547
+ pgconn_finish( VALUE self )
548
+ {
549
+ t_pg_connection *this = pg_get_connection_safe( self );
550
+
551
+ pgconn_close_socket_io( self );
552
+ PQfinish( this->pgconn );
553
+ this->pgconn = NULL;
554
+ return Qnil;
555
+ }
556
+
557
+
558
+ /*
559
+ * call-seq:
560
+ * conn.finished? -> boolean
561
+ *
562
+ * Returns +true+ if the backend connection has been closed.
563
+ */
564
+ static VALUE
565
+ pgconn_finished_p( VALUE self )
566
+ {
567
+ t_pg_connection *this = pg_get_connection( self );
568
+ if ( this->pgconn ) return Qfalse;
569
+ return Qtrue;
570
+ }
571
+
572
+
573
+ /*
574
+ * call-seq:
575
+ * conn.reset()
576
+ *
577
+ * Resets the backend connection. This method closes the
578
+ * backend connection and tries to re-connect.
579
+ */
580
+ static VALUE
581
+ pgconn_reset( VALUE self )
582
+ {
583
+ pgconn_close_socket_io( self );
584
+ gvl_PQreset( pg_get_pgconn(self) );
585
+ return self;
586
+ }
587
+
588
+ /*
589
+ * call-seq:
590
+ * conn.reset_start() -> nil
591
+ *
592
+ * Initiate a connection reset in a nonblocking manner.
593
+ * This will close the current connection and attempt to
594
+ * reconnect using the same connection parameters.
595
+ * Use #reset_poll to check the status of the
596
+ * connection reset.
597
+ */
598
+ static VALUE
599
+ pgconn_reset_start(VALUE self)
600
+ {
601
+ pgconn_close_socket_io( self );
602
+ if(gvl_PQresetStart(pg_get_pgconn(self)) == 0)
603
+ rb_raise(rb_eUnableToSend, "reset has failed");
604
+ return Qnil;
605
+ }
606
+
607
+ /*
608
+ * call-seq:
609
+ * conn.reset_poll -> Integer
610
+ *
611
+ * Checks the status of a connection reset operation.
612
+ * See #connect_start and #connect_poll for
613
+ * usage information and return values.
614
+ */
615
+ static VALUE
616
+ pgconn_reset_poll(VALUE self)
617
+ {
618
+ PostgresPollingStatusType status;
619
+ status = gvl_PQresetPoll(pg_get_pgconn(self));
620
+ return INT2FIX((int)status);
621
+ }
622
+
623
+
624
+ /*
625
+ * call-seq:
626
+ * conn.db()
627
+ *
628
+ * Returns the connected database name.
629
+ */
630
+ static VALUE
631
+ pgconn_db(VALUE self)
632
+ {
633
+ char *db = PQdb(pg_get_pgconn(self));
634
+ if (!db) return Qnil;
635
+ return rb_tainted_str_new2(db);
636
+ }
637
+
638
+ /*
639
+ * call-seq:
640
+ * conn.user()
641
+ *
642
+ * Returns the authenticated user name.
643
+ */
644
+ static VALUE
645
+ pgconn_user(VALUE self)
646
+ {
647
+ char *user = PQuser(pg_get_pgconn(self));
648
+ if (!user) return Qnil;
649
+ return rb_tainted_str_new2(user);
650
+ }
651
+
652
+ /*
653
+ * call-seq:
654
+ * conn.pass()
655
+ *
656
+ * Returns the authenticated password.
657
+ */
658
+ static VALUE
659
+ pgconn_pass(VALUE self)
660
+ {
661
+ char *user = PQpass(pg_get_pgconn(self));
662
+ if (!user) return Qnil;
663
+ return rb_tainted_str_new2(user);
664
+ }
665
+
666
+ /*
667
+ * call-seq:
668
+ * conn.host()
669
+ *
670
+ * Returns the connected server name.
671
+ */
672
+ static VALUE
673
+ pgconn_host(VALUE self)
674
+ {
675
+ char *host = PQhost(pg_get_pgconn(self));
676
+ if (!host) return Qnil;
677
+ return rb_tainted_str_new2(host);
678
+ }
679
+
680
+ /*
681
+ * call-seq:
682
+ * conn.port()
683
+ *
684
+ * Returns the connected server port number.
685
+ */
686
+ static VALUE
687
+ pgconn_port(VALUE self)
688
+ {
689
+ char* port = PQport(pg_get_pgconn(self));
690
+ return INT2NUM(atol(port));
691
+ }
692
+
693
+ /*
694
+ * call-seq:
695
+ * conn.tty()
696
+ *
697
+ * Returns the connected pgtty. (Obsolete)
698
+ */
699
+ static VALUE
700
+ pgconn_tty(VALUE self)
701
+ {
702
+ char *tty = PQtty(pg_get_pgconn(self));
703
+ if (!tty) return Qnil;
704
+ return rb_tainted_str_new2(tty);
705
+ }
706
+
707
+ /*
708
+ * call-seq:
709
+ * conn.options()
710
+ *
711
+ * Returns backend option string.
712
+ */
713
+ static VALUE
714
+ pgconn_options(VALUE self)
715
+ {
716
+ char *options = PQoptions(pg_get_pgconn(self));
717
+ if (!options) return Qnil;
718
+ return rb_tainted_str_new2(options);
719
+ }
720
+
721
+
722
+ #ifdef HAVE_PQCONNINFO
723
+ /*
724
+ * call-seq:
725
+ * conn.conninfo -> hash
726
+ *
727
+ * Returns the connection options used by a live connection.
728
+ *
729
+ * Available since PostgreSQL-9.3
730
+ */
731
+ static VALUE
732
+ pgconn_conninfo( VALUE self )
733
+ {
734
+ PGconn *conn = pg_get_pgconn(self);
735
+ PQconninfoOption *options = PQconninfo( conn );
736
+ VALUE array = pgconn_make_conninfo_array( options );
737
+
738
+ PQconninfoFree(options);
739
+
740
+ return array;
741
+ }
742
+ #endif
743
+
744
+
745
+ /*
746
+ * call-seq:
747
+ * conn.status()
748
+ *
749
+ * Returns status of connection : CONNECTION_OK or CONNECTION_BAD
750
+ */
751
+ static VALUE
752
+ pgconn_status(VALUE self)
753
+ {
754
+ return INT2NUM(PQstatus(pg_get_pgconn(self)));
755
+ }
756
+
757
+ /*
758
+ * call-seq:
759
+ * conn.transaction_status()
760
+ *
761
+ * returns one of the following statuses:
762
+ * PQTRANS_IDLE = 0 (connection idle)
763
+ * PQTRANS_ACTIVE = 1 (command in progress)
764
+ * PQTRANS_INTRANS = 2 (idle, within transaction block)
765
+ * PQTRANS_INERROR = 3 (idle, within failed transaction)
766
+ * PQTRANS_UNKNOWN = 4 (cannot determine status)
767
+ */
768
+ static VALUE
769
+ pgconn_transaction_status(VALUE self)
770
+ {
771
+ return INT2NUM(PQtransactionStatus(pg_get_pgconn(self)));
772
+ }
773
+
774
+ /*
775
+ * call-seq:
776
+ * conn.parameter_status( param_name ) -> String
777
+ *
778
+ * Returns the setting of parameter _param_name_, where
779
+ * _param_name_ is one of
780
+ * * +server_version+
781
+ * * +server_encoding+
782
+ * * +client_encoding+
783
+ * * +is_superuser+
784
+ * * +session_authorization+
785
+ * * +DateStyle+
786
+ * * +TimeZone+
787
+ * * +integer_datetimes+
788
+ * * +standard_conforming_strings+
789
+ *
790
+ * Returns nil if the value of the parameter is not known.
791
+ */
792
+ static VALUE
793
+ pgconn_parameter_status(VALUE self, VALUE param_name)
794
+ {
795
+ const char *ret = PQparameterStatus(pg_get_pgconn(self), StringValueCStr(param_name));
796
+ if(ret == NULL)
797
+ return Qnil;
798
+ else
799
+ return rb_tainted_str_new2(ret);
800
+ }
801
+
802
+ /*
803
+ * call-seq:
804
+ * conn.protocol_version -> Integer
805
+ *
806
+ * The 3.0 protocol will normally be used when communicating with PostgreSQL 7.4
807
+ * or later servers; pre-7.4 servers support only protocol 2.0. (Protocol 1.0 is
808
+ * obsolete and not supported by libpq.)
809
+ */
810
+ static VALUE
811
+ pgconn_protocol_version(VALUE self)
812
+ {
813
+ return INT2NUM(PQprotocolVersion(pg_get_pgconn(self)));
814
+ }
815
+
816
+ /*
817
+ * call-seq:
818
+ * conn.server_version -> Integer
819
+ *
820
+ * The number is formed by converting the major, minor, and revision
821
+ * numbers into two-decimal-digit numbers and appending them together.
822
+ * For example, version 7.4.2 will be returned as 70402, and version
823
+ * 8.1 will be returned as 80100 (leading zeroes are not shown). Zero
824
+ * is returned if the connection is bad.
825
+ *
826
+ */
827
+ static VALUE
828
+ pgconn_server_version(VALUE self)
829
+ {
830
+ return INT2NUM(PQserverVersion(pg_get_pgconn(self)));
831
+ }
832
+
833
+ /*
834
+ * call-seq:
835
+ * conn.error_message -> String
836
+ *
837
+ * Returns the error message about connection.
838
+ */
839
+ static VALUE
840
+ pgconn_error_message(VALUE self)
841
+ {
842
+ char *error = PQerrorMessage(pg_get_pgconn(self));
843
+ if (!error) return Qnil;
844
+ return rb_tainted_str_new2(error);
845
+ }
846
+
847
+ /*
848
+ * call-seq:
849
+ * conn.socket() -> Integer
850
+ *
851
+ * This method is deprecated. Please use the more portable method #socket_io .
852
+ *
853
+ * Returns the socket's file descriptor for this connection.
854
+ * <tt>IO.for_fd()</tt> can be used to build a proper IO object to the socket.
855
+ * If you do so, you will likely also want to set <tt>autoclose=false</tt>
856
+ * on it to prevent Ruby from closing the socket to PostgreSQL if it
857
+ * goes out of scope. Alternatively, you can use #socket_io, which
858
+ * creates an IO that's associated with the connection object itself,
859
+ * and so won't go out of scope until the connection does.
860
+ *
861
+ * *Note:* On Windows the file descriptor is not usable,
862
+ * since it can not be used to build a Ruby IO object.
863
+ */
864
+ static VALUE
865
+ pgconn_socket(VALUE self)
866
+ {
867
+ int sd;
868
+ if( (sd = PQsocket(pg_get_pgconn(self))) < 0)
869
+ rb_raise(rb_eConnectionBad, "PQsocket() can't get socket descriptor");
870
+ return INT2NUM(sd);
871
+ }
872
+
873
+ /*
874
+ * call-seq:
875
+ * conn.socket_io() -> IO
876
+ *
877
+ * Fetch a memorized IO object created from the Connection's underlying socket.
878
+ * This object can be used for IO.select to wait for events while running
879
+ * asynchronous API calls.
880
+ *
881
+ * Using this instead of #socket avoids the problem of the underlying connection
882
+ * being closed by Ruby when an IO created using <tt>IO.for_fd(conn.socket)</tt>
883
+ * goes out of scope. In contrast to #socket, it also works on Windows.
884
+ */
885
+ static VALUE
886
+ pgconn_socket_io(VALUE self)
887
+ {
888
+ int sd;
889
+ int ruby_sd;
890
+ ID id_autoclose = rb_intern("autoclose=");
891
+ t_pg_connection *this = pg_get_connection_safe( self );
892
+ VALUE socket_io = this->socket_io;
893
+
894
+ if ( !RTEST(socket_io) ) {
895
+ if( (sd = PQsocket(this->pgconn)) < 0)
896
+ rb_raise(rb_eConnectionBad, "PQsocket() can't get socket descriptor");
897
+
898
+ #ifdef _WIN32
899
+ ruby_sd = rb_w32_wrap_io_handle((HANDLE)(intptr_t)sd, O_RDWR|O_BINARY|O_NOINHERIT);
900
+ this->ruby_sd = ruby_sd;
901
+ #else
902
+ ruby_sd = sd;
903
+ #endif
904
+
905
+ socket_io = rb_funcall( rb_cIO, rb_intern("for_fd"), 1, INT2NUM(ruby_sd) );
906
+
907
+ /* Disable autoclose feature */
908
+ rb_funcall( socket_io, id_autoclose, 1, Qfalse );
909
+
910
+ this->socket_io = socket_io;
911
+ }
912
+
913
+ return socket_io;
914
+ }
915
+
916
+ /*
917
+ * call-seq:
918
+ * conn.backend_pid() -> Integer
919
+ *
920
+ * Returns the process ID of the backend server
921
+ * process for this connection.
922
+ * Note that this is a PID on database server host.
923
+ */
924
+ static VALUE
925
+ pgconn_backend_pid(VALUE self)
926
+ {
927
+ return INT2NUM(PQbackendPID(pg_get_pgconn(self)));
928
+ }
929
+
930
+ /*
931
+ * call-seq:
932
+ * conn.connection_needs_password() -> Boolean
933
+ *
934
+ * Returns +true+ if the authentication method required a
935
+ * password, but none was available. +false+ otherwise.
936
+ */
937
+ static VALUE
938
+ pgconn_connection_needs_password(VALUE self)
939
+ {
940
+ return PQconnectionNeedsPassword(pg_get_pgconn(self)) ? Qtrue : Qfalse;
941
+ }
942
+
943
+ /*
944
+ * call-seq:
945
+ * conn.connection_used_password() -> Boolean
946
+ *
947
+ * Returns +true+ if the authentication method used
948
+ * a caller-supplied password, +false+ otherwise.
949
+ */
950
+ static VALUE
951
+ pgconn_connection_used_password(VALUE self)
952
+ {
953
+ return PQconnectionUsedPassword(pg_get_pgconn(self)) ? Qtrue : Qfalse;
954
+ }
955
+
956
+
957
+ /* :TODO: get_ssl */
958
+
959
+
960
+ static VALUE pgconn_exec_params( int, VALUE *, VALUE );
961
+
962
+ /*
963
+ * call-seq:
964
+ * conn.exec(sql) -> PG::Result
965
+ * conn.exec(sql) {|pg_result| block }
966
+ *
967
+ * Sends SQL query request specified by _sql_ to PostgreSQL.
968
+ * On success, it returns a PG::Result instance with all result rows and columns.
969
+ * On failure, it raises a PG::Error.
970
+ *
971
+ * For backward compatibility, if you pass more than one parameter to this method,
972
+ * it will call #exec_params for you. New code should explicitly use #exec_params if
973
+ * argument placeholders are used.
974
+ *
975
+ * If the optional code block is given, it will be passed <i>result</i> as an argument,
976
+ * and the PG::Result object will automatically be cleared when the block terminates.
977
+ * In this instance, <code>conn.exec</code> returns the value of the block.
978
+ *
979
+ * #sync_exec is implemented on the synchronous command processing API of libpq, whereas
980
+ * #async_exec is implemented on the asynchronous API.
981
+ * #sync_exec is somewhat faster that #async_exec, but blocks any signals to be processed until
982
+ * the query is finished. This is most notably visible by a delayed reaction to Control+C.
983
+ * Both methods ensure that other threads can process while waiting for the server to
984
+ * complete the request.
985
+ */
986
+ static VALUE
987
+ pgconn_exec(int argc, VALUE *argv, VALUE self)
988
+ {
989
+ PGconn *conn = pg_get_pgconn(self);
990
+ PGresult *result = NULL;
991
+ VALUE rb_pgresult;
992
+
993
+ /* If called with no or nil parameters, use PQexec for compatibility */
994
+ if ( argc == 1 || (argc >= 2 && argc <= 4 && NIL_P(argv[1]) )) {
995
+ VALUE query_str = argv[0];
996
+
997
+ result = gvl_PQexec(conn, pg_cstr_enc(query_str, ENCODING_GET(self)));
998
+ rb_pgresult = pg_new_result(result, self);
999
+ pg_result_check(rb_pgresult);
1000
+ if (rb_block_given_p()) {
1001
+ return rb_ensure(rb_yield, rb_pgresult, pg_result_clear, rb_pgresult);
1002
+ }
1003
+ return rb_pgresult;
1004
+ }
1005
+ pg_deprecated(0, ("forwarding exec to exec_params is deprecated"));
1006
+
1007
+ /* Otherwise, just call #exec_params instead for backward-compatibility */
1008
+ return pgconn_exec_params( argc, argv, self );
1009
+
1010
+ }
1011
+
1012
+
1013
+ struct linked_typecast_data {
1014
+ struct linked_typecast_data *next;
1015
+ char data[0];
1016
+ };
1017
+
1018
+ /* This struct is allocated on the stack for all query execution functions. */
1019
+ struct query_params_data {
1020
+
1021
+ /*
1022
+ * Filled by caller
1023
+ */
1024
+
1025
+ /* The character encoding index of the connection. Any strings
1026
+ * given as query parameters are converted to this encoding.
1027
+ */
1028
+ int enc_idx;
1029
+ /* Is the query function to execute one with types array? */
1030
+ int with_types;
1031
+ /* Array of query params from user space */
1032
+ VALUE params;
1033
+ /* The typemap given from user space */
1034
+ VALUE typemap;
1035
+
1036
+ /*
1037
+ * Filled by alloc_query_params()
1038
+ */
1039
+
1040
+ /* Wraps the pointer of allocated memory, if function parameters dont't
1041
+ * fit in the memory_pool below.
1042
+ */
1043
+ VALUE heap_pool;
1044
+
1045
+ /* Pointer to the value string pointers (either within memory_pool or heap_pool).
1046
+ * The value strings itself are either directly within RString memory or,
1047
+ * in case of type casted values, within memory_pool or typecast_heap_chain.
1048
+ */
1049
+ char **values;
1050
+ /* Pointer to the param lengths (either within memory_pool or heap_pool) */
1051
+ int *lengths;
1052
+ /* Pointer to the format codes (either within memory_pool or heap_pool) */
1053
+ int *formats;
1054
+ /* Pointer to the OID types (either within memory_pool or heap_pool) */
1055
+ Oid *types;
1056
+
1057
+ /* This array takes the string values for the timeframe of the query,
1058
+ * if param value convertion is required
1059
+ */
1060
+ VALUE gc_array;
1061
+
1062
+ /* Wraps a single linked list of allocated memory chunks for type casted params.
1063
+ * Used when the memory_pool is to small.
1064
+ */
1065
+ VALUE typecast_heap_chain;
1066
+
1067
+ /* This memory pool is used to place above query function parameters on it. */
1068
+ char memory_pool[QUERYDATA_BUFFER_SIZE];
1069
+ };
1070
+
1071
+ static void
1072
+ free_typecast_heap_chain(struct linked_typecast_data *chain_entry)
1073
+ {
1074
+ while(chain_entry){
1075
+ struct linked_typecast_data *next = chain_entry->next;
1076
+ xfree(chain_entry);
1077
+ chain_entry = next;
1078
+ }
1079
+ }
1080
+
1081
+ static char *
1082
+ alloc_typecast_buf( VALUE *typecast_heap_chain, int len )
1083
+ {
1084
+ /* Allocate a new memory chunk from heap */
1085
+ struct linked_typecast_data *allocated =
1086
+ (struct linked_typecast_data *)xmalloc(sizeof(struct linked_typecast_data) + len);
1087
+
1088
+ /* Did we already wrap a memory chain per T_DATA object? */
1089
+ if( NIL_P( *typecast_heap_chain ) ){
1090
+ /* Leave free'ing of the buffer chain to the GC, when paramsData has left the stack */
1091
+ *typecast_heap_chain = Data_Wrap_Struct( rb_cObject, NULL, free_typecast_heap_chain, allocated );
1092
+ allocated->next = NULL;
1093
+ } else {
1094
+ /* Append to the chain */
1095
+ allocated->next = DATA_PTR( *typecast_heap_chain );
1096
+ DATA_PTR( *typecast_heap_chain ) = allocated;
1097
+ }
1098
+
1099
+ return &allocated->data[0];
1100
+ }
1101
+
1102
+
1103
+ static int
1104
+ alloc_query_params(struct query_params_data *paramsData)
1105
+ {
1106
+ VALUE param_value;
1107
+ t_typemap *p_typemap;
1108
+ int nParams;
1109
+ int i=0;
1110
+ t_pg_coder *conv;
1111
+ unsigned int required_pool_size;
1112
+ char *memory_pool;
1113
+
1114
+ Check_Type(paramsData->params, T_ARRAY);
1115
+
1116
+ p_typemap = DATA_PTR( paramsData->typemap );
1117
+ p_typemap->funcs.fit_to_query( paramsData->typemap, paramsData->params );
1118
+
1119
+ paramsData->heap_pool = Qnil;
1120
+ paramsData->typecast_heap_chain = Qnil;
1121
+ paramsData->gc_array = Qnil;
1122
+
1123
+ nParams = (int)RARRAY_LEN(paramsData->params);
1124
+
1125
+ required_pool_size = nParams * (
1126
+ sizeof(char *) +
1127
+ sizeof(int) +
1128
+ sizeof(int) +
1129
+ (paramsData->with_types ? sizeof(Oid) : 0));
1130
+
1131
+ if( sizeof(paramsData->memory_pool) < required_pool_size ){
1132
+ /* Allocate one combined memory pool for all possible function parameters */
1133
+ memory_pool = (char*)xmalloc( required_pool_size );
1134
+ /* Leave free'ing of the buffer to the GC, when paramsData has left the stack */
1135
+ paramsData->heap_pool = Data_Wrap_Struct( rb_cObject, NULL, -1, memory_pool );
1136
+ required_pool_size = 0;
1137
+ }else{
1138
+ /* Use stack memory for function parameters */
1139
+ memory_pool = paramsData->memory_pool;
1140
+ }
1141
+
1142
+ paramsData->values = (char **)memory_pool;
1143
+ paramsData->lengths = (int *)((char*)paramsData->values + sizeof(char *) * nParams);
1144
+ paramsData->formats = (int *)((char*)paramsData->lengths + sizeof(int) * nParams);
1145
+ paramsData->types = (Oid *)((char*)paramsData->formats + sizeof(int) * nParams);
1146
+
1147
+ {
1148
+ char *typecast_buf = paramsData->memory_pool + required_pool_size;
1149
+
1150
+ for ( i = 0; i < nParams; i++ ) {
1151
+ param_value = rb_ary_entry(paramsData->params, i);
1152
+
1153
+ paramsData->formats[i] = 0;
1154
+ if( paramsData->with_types )
1155
+ paramsData->types[i] = 0;
1156
+
1157
+ /* Let the given typemap select a coder for this param */
1158
+ conv = p_typemap->funcs.typecast_query_param(p_typemap, param_value, i);
1159
+
1160
+ /* Using a coder object for the param_value? Then set it's format code and oid. */
1161
+ if( conv ){
1162
+ paramsData->formats[i] = conv->format;
1163
+ if( paramsData->with_types )
1164
+ paramsData->types[i] = conv->oid;
1165
+ } else {
1166
+ /* No coder, but got we a hash form for the query param?
1167
+ * Then take format code and oid from there. */
1168
+ if (TYPE(param_value) == T_HASH) {
1169
+ VALUE format_value = rb_hash_aref(param_value, sym_format);
1170
+ if( !NIL_P(format_value) )
1171
+ paramsData->formats[i] = NUM2INT(format_value);
1172
+ if( paramsData->with_types ){
1173
+ VALUE type_value = rb_hash_aref(param_value, sym_type);
1174
+ if( !NIL_P(type_value) )
1175
+ paramsData->types[i] = NUM2UINT(type_value);
1176
+ }
1177
+ param_value = rb_hash_aref(param_value, sym_value);
1178
+ }
1179
+ }
1180
+
1181
+ if( NIL_P(param_value) ){
1182
+ paramsData->values[i] = NULL;
1183
+ paramsData->lengths[i] = 0;
1184
+ } else {
1185
+ t_pg_coder_enc_func enc_func = pg_coder_enc_func( conv );
1186
+ VALUE intermediate;
1187
+
1188
+ /* 1st pass for retiving the required memory space */
1189
+ int len = enc_func(conv, param_value, NULL, &intermediate, paramsData->enc_idx);
1190
+
1191
+ if( len == -1 ){
1192
+ /* The intermediate value is a String that can be used directly. */
1193
+
1194
+ /* Ensure that the String object is zero terminated as expected by libpq. */
1195
+ if( paramsData->formats[i] == 0 )
1196
+ StringValueCStr(intermediate);
1197
+ /* In case a new string object was generated, make sure it doesn't get freed by the GC */
1198
+ if( intermediate != param_value ){
1199
+ if( NIL_P(paramsData->gc_array) )
1200
+ paramsData->gc_array = rb_ary_new();
1201
+ rb_ary_push(paramsData->gc_array, intermediate);
1202
+ }
1203
+ paramsData->values[i] = RSTRING_PTR(intermediate);
1204
+ paramsData->lengths[i] = RSTRING_LENINT(intermediate);
1205
+
1206
+ } else {
1207
+ /* Is the stack memory pool too small to take the type casted value? */
1208
+ if( sizeof(paramsData->memory_pool) < required_pool_size + len + 1){
1209
+ typecast_buf = alloc_typecast_buf( &paramsData->typecast_heap_chain, len + 1 );
1210
+ }
1211
+
1212
+ /* 2nd pass for writing the data to prepared buffer */
1213
+ len = enc_func(conv, param_value, typecast_buf, &intermediate, paramsData->enc_idx);
1214
+ paramsData->values[i] = typecast_buf;
1215
+ if( paramsData->formats[i] == 0 ){
1216
+ /* text format strings must be zero terminated and lengths are ignored */
1217
+ typecast_buf[len] = 0;
1218
+ typecast_buf += len + 1;
1219
+ required_pool_size += len + 1;
1220
+ } else {
1221
+ paramsData->lengths[i] = len;
1222
+ typecast_buf += len;
1223
+ required_pool_size += len;
1224
+ }
1225
+ }
1226
+
1227
+ RB_GC_GUARD(intermediate);
1228
+ }
1229
+ }
1230
+ }
1231
+
1232
+ return nParams;
1233
+ }
1234
+
1235
+ static void
1236
+ free_query_params(struct query_params_data *paramsData)
1237
+ {
1238
+ /* currently nothing to free */
1239
+ }
1240
+
1241
+ void
1242
+ pgconn_query_assign_typemap( VALUE self, struct query_params_data *paramsData )
1243
+ {
1244
+ if(NIL_P(paramsData->typemap)){
1245
+ /* Use default typemap for queries. It's type is checked when assigned. */
1246
+ paramsData->typemap = pg_get_connection(self)->type_map_for_queries;
1247
+ }else{
1248
+ /* Check type of method param */
1249
+ if ( !rb_obj_is_kind_of(paramsData->typemap, rb_cTypeMap) ) {
1250
+ rb_raise( rb_eTypeError, "wrong argument type %s (expected kind of PG::TypeMap)",
1251
+ rb_obj_classname( paramsData->typemap ) );
1252
+ }
1253
+ Check_Type( paramsData->typemap, T_DATA );
1254
+ }
1255
+ }
1256
+
1257
+ /*
1258
+ * call-seq:
1259
+ * conn.exec_params(sql, params[, result_format[, type_map]] ) -> PG::Result
1260
+ * conn.exec_params(sql, params[, result_format[, type_map]] ) {|pg_result| block }
1261
+ *
1262
+ * Sends SQL query request specified by +sql+ to PostgreSQL using placeholders
1263
+ * for parameters.
1264
+ *
1265
+ * Returns a PG::Result instance on success. On failure, it raises a PG::Error.
1266
+ *
1267
+ * +params+ is an array of the bind parameters for the SQL query.
1268
+ * Each element of the +params+ array may be either:
1269
+ * a hash of the form:
1270
+ * {:value => String (value of bind parameter)
1271
+ * :type => Integer (oid of type of bind parameter)
1272
+ * :format => Integer (0 for text, 1 for binary)
1273
+ * }
1274
+ * or, it may be a String. If it is a string, that is equivalent to the hash:
1275
+ * { :value => <string value>, :type => 0, :format => 0 }
1276
+ *
1277
+ * PostgreSQL bind parameters are represented as $1, $1, $2, etc.,
1278
+ * inside the SQL query. The 0th element of the +params+ array is bound
1279
+ * to $1, the 1st element is bound to $2, etc. +nil+ is treated as +NULL+.
1280
+ *
1281
+ * If the types are not specified, they will be inferred by PostgreSQL.
1282
+ * Instead of specifying type oids, it's recommended to simply add
1283
+ * explicit casts in the query to ensure that the right type is used.
1284
+ *
1285
+ * For example: "SELECT $1::int"
1286
+ *
1287
+ * The optional +result_format+ should be 0 for text results, 1
1288
+ * for binary.
1289
+ *
1290
+ * type_map can be a PG::TypeMap derivation (such as PG::BasicTypeMapForQueries).
1291
+ * This will type cast the params from various Ruby types before transmission
1292
+ * based on the encoders defined by the type map. When a type encoder is used
1293
+ * the format and oid of a given bind parameter are retrieved from the encoder
1294
+ * instead out of the hash form described above.
1295
+ *
1296
+ * If the optional code block is given, it will be passed <i>result</i> as an argument,
1297
+ * and the PG::Result object will automatically be cleared when the block terminates.
1298
+ * In this instance, <code>conn.exec</code> returns the value of the block.
1299
+ */
1300
+ static VALUE
1301
+ pgconn_exec_params( int argc, VALUE *argv, VALUE self )
1302
+ {
1303
+ PGconn *conn = pg_get_pgconn(self);
1304
+ PGresult *result = NULL;
1305
+ VALUE rb_pgresult;
1306
+ VALUE command, in_res_fmt;
1307
+ int nParams;
1308
+ int resultFormat;
1309
+ struct query_params_data paramsData = { ENCODING_GET(self) };
1310
+
1311
+ /* For compatibility we accept 1 to 4 parameters */
1312
+ rb_scan_args(argc, argv, "13", &command, &paramsData.params, &in_res_fmt, &paramsData.typemap);
1313
+ paramsData.with_types = 1;
1314
+
1315
+ /*
1316
+ * For backward compatibility no or +nil+ for the second parameter
1317
+ * is passed to #exec
1318
+ */
1319
+ if ( NIL_P(paramsData.params) ) {
1320
+ pg_deprecated(1, ("forwarding exec_params to exec is deprecated"));
1321
+ return pgconn_exec( 1, argv, self );
1322
+ }
1323
+ pgconn_query_assign_typemap( self, &paramsData );
1324
+
1325
+ resultFormat = NIL_P(in_res_fmt) ? 0 : NUM2INT(in_res_fmt);
1326
+ nParams = alloc_query_params( &paramsData );
1327
+
1328
+ result = gvl_PQexecParams(conn, pg_cstr_enc(command, paramsData.enc_idx), nParams, paramsData.types,
1329
+ (const char * const *)paramsData.values, paramsData.lengths, paramsData.formats, resultFormat);
1330
+
1331
+ free_query_params( &paramsData );
1332
+
1333
+ rb_pgresult = pg_new_result(result, self);
1334
+ pg_result_check(rb_pgresult);
1335
+
1336
+ if (rb_block_given_p()) {
1337
+ return rb_ensure(rb_yield, rb_pgresult, pg_result_clear, rb_pgresult);
1338
+ }
1339
+
1340
+ return rb_pgresult;
1341
+ }
1342
+
1343
+ /*
1344
+ * call-seq:
1345
+ * conn.prepare(stmt_name, sql [, param_types ] ) -> PG::Result
1346
+ *
1347
+ * Prepares statement _sql_ with name _name_ to be executed later.
1348
+ * Returns a PG::Result instance on success.
1349
+ * On failure, it raises a PG::Error.
1350
+ *
1351
+ * +param_types+ is an optional parameter to specify the Oids of the
1352
+ * types of the parameters.
1353
+ *
1354
+ * If the types are not specified, they will be inferred by PostgreSQL.
1355
+ * Instead of specifying type oids, it's recommended to simply add
1356
+ * explicit casts in the query to ensure that the right type is used.
1357
+ *
1358
+ * For example: "SELECT $1::int"
1359
+ *
1360
+ * PostgreSQL bind parameters are represented as $1, $1, $2, etc.,
1361
+ * inside the SQL query.
1362
+ */
1363
+ static VALUE
1364
+ pgconn_prepare(int argc, VALUE *argv, VALUE self)
1365
+ {
1366
+ PGconn *conn = pg_get_pgconn(self);
1367
+ PGresult *result = NULL;
1368
+ VALUE rb_pgresult;
1369
+ VALUE name, command, in_paramtypes;
1370
+ VALUE param;
1371
+ int i = 0;
1372
+ int nParams = 0;
1373
+ Oid *paramTypes = NULL;
1374
+ const char *name_cstr;
1375
+ const char *command_cstr;
1376
+ int enc_idx = ENCODING_GET(self);
1377
+
1378
+ rb_scan_args(argc, argv, "21", &name, &command, &in_paramtypes);
1379
+ name_cstr = pg_cstr_enc(name, enc_idx);
1380
+ command_cstr = pg_cstr_enc(command, enc_idx);
1381
+
1382
+ if(! NIL_P(in_paramtypes)) {
1383
+ Check_Type(in_paramtypes, T_ARRAY);
1384
+ nParams = (int)RARRAY_LEN(in_paramtypes);
1385
+ paramTypes = ALLOC_N(Oid, nParams);
1386
+ for(i = 0; i < nParams; i++) {
1387
+ param = rb_ary_entry(in_paramtypes, i);
1388
+ if(param == Qnil)
1389
+ paramTypes[i] = 0;
1390
+ else
1391
+ paramTypes[i] = NUM2UINT(param);
1392
+ }
1393
+ }
1394
+ result = gvl_PQprepare(conn, name_cstr, command_cstr, nParams, paramTypes);
1395
+
1396
+ xfree(paramTypes);
1397
+
1398
+ rb_pgresult = pg_new_result(result, self);
1399
+ pg_result_check(rb_pgresult);
1400
+ return rb_pgresult;
1401
+ }
1402
+
1403
+ /*
1404
+ * call-seq:
1405
+ * conn.exec_prepared(statement_name [, params, result_format[, type_map]] ) -> PG::Result
1406
+ * conn.exec_prepared(statement_name [, params, result_format[, type_map]] ) {|pg_result| block }
1407
+ *
1408
+ * Execute prepared named statement specified by _statement_name_.
1409
+ * Returns a PG::Result instance on success.
1410
+ * On failure, it raises a PG::Error.
1411
+ *
1412
+ * +params+ is an array of the optional bind parameters for the
1413
+ * SQL query. Each element of the +params+ array may be either:
1414
+ * a hash of the form:
1415
+ * {:value => String (value of bind parameter)
1416
+ * :format => Integer (0 for text, 1 for binary)
1417
+ * }
1418
+ * or, it may be a String. If it is a string, that is equivalent to the hash:
1419
+ * { :value => <string value>, :format => 0 }
1420
+ *
1421
+ * PostgreSQL bind parameters are represented as $1, $1, $2, etc.,
1422
+ * inside the SQL query. The 0th element of the +params+ array is bound
1423
+ * to $1, the 1st element is bound to $2, etc. +nil+ is treated as +NULL+.
1424
+ *
1425
+ * The optional +result_format+ should be 0 for text results, 1
1426
+ * for binary.
1427
+ *
1428
+ * type_map can be a PG::TypeMap derivation (such as PG::BasicTypeMapForQueries).
1429
+ * This will type cast the params from various Ruby types before transmission
1430
+ * based on the encoders defined by the type map. When a type encoder is used
1431
+ * the format and oid of a given bind parameter are retrieved from the encoder
1432
+ * instead out of the hash form described above.
1433
+ *
1434
+ * If the optional code block is given, it will be passed <i>result</i> as an argument,
1435
+ * and the PG::Result object will automatically be cleared when the block terminates.
1436
+ * In this instance, <code>conn.exec_prepared</code> returns the value of the block.
1437
+ */
1438
+ static VALUE
1439
+ pgconn_exec_prepared(int argc, VALUE *argv, VALUE self)
1440
+ {
1441
+ PGconn *conn = pg_get_pgconn(self);
1442
+ PGresult *result = NULL;
1443
+ VALUE rb_pgresult;
1444
+ VALUE name, in_res_fmt;
1445
+ int nParams;
1446
+ int resultFormat;
1447
+ struct query_params_data paramsData = { ENCODING_GET(self) };
1448
+
1449
+ rb_scan_args(argc, argv, "13", &name, &paramsData.params, &in_res_fmt, &paramsData.typemap);
1450
+ paramsData.with_types = 0;
1451
+
1452
+ if(NIL_P(paramsData.params)) {
1453
+ paramsData.params = rb_ary_new2(0);
1454
+ }
1455
+ pgconn_query_assign_typemap( self, &paramsData );
1456
+
1457
+ resultFormat = NIL_P(in_res_fmt) ? 0 : NUM2INT(in_res_fmt);
1458
+ nParams = alloc_query_params( &paramsData );
1459
+
1460
+ result = gvl_PQexecPrepared(conn, pg_cstr_enc(name, paramsData.enc_idx), nParams,
1461
+ (const char * const *)paramsData.values, paramsData.lengths, paramsData.formats,
1462
+ resultFormat);
1463
+
1464
+ free_query_params( &paramsData );
1465
+
1466
+ rb_pgresult = pg_new_result(result, self);
1467
+ pg_result_check(rb_pgresult);
1468
+ if (rb_block_given_p()) {
1469
+ return rb_ensure(rb_yield, rb_pgresult,
1470
+ pg_result_clear, rb_pgresult);
1471
+ }
1472
+ return rb_pgresult;
1473
+ }
1474
+
1475
+ /*
1476
+ * call-seq:
1477
+ * conn.describe_prepared( statement_name ) -> PG::Result
1478
+ *
1479
+ * Retrieve information about the prepared statement
1480
+ * _statement_name_.
1481
+ */
1482
+ static VALUE
1483
+ pgconn_describe_prepared(VALUE self, VALUE stmt_name)
1484
+ {
1485
+ PGresult *result;
1486
+ VALUE rb_pgresult;
1487
+ PGconn *conn = pg_get_pgconn(self);
1488
+ const char *stmt;
1489
+ if(NIL_P(stmt_name)) {
1490
+ stmt = NULL;
1491
+ }
1492
+ else {
1493
+ stmt = pg_cstr_enc(stmt_name, ENCODING_GET(self));
1494
+ }
1495
+ result = gvl_PQdescribePrepared(conn, stmt);
1496
+ rb_pgresult = pg_new_result(result, self);
1497
+ pg_result_check(rb_pgresult);
1498
+ return rb_pgresult;
1499
+ }
1500
+
1501
+
1502
+ /*
1503
+ * call-seq:
1504
+ * conn.describe_portal( portal_name ) -> PG::Result
1505
+ *
1506
+ * Retrieve information about the portal _portal_name_.
1507
+ */
1508
+ static VALUE
1509
+ pgconn_describe_portal(self, stmt_name)
1510
+ VALUE self, stmt_name;
1511
+ {
1512
+ PGresult *result;
1513
+ VALUE rb_pgresult;
1514
+ PGconn *conn = pg_get_pgconn(self);
1515
+ const char *stmt;
1516
+ if(NIL_P(stmt_name)) {
1517
+ stmt = NULL;
1518
+ }
1519
+ else {
1520
+ stmt = pg_cstr_enc(stmt_name, ENCODING_GET(self));
1521
+ }
1522
+ result = gvl_PQdescribePortal(conn, stmt);
1523
+ rb_pgresult = pg_new_result(result, self);
1524
+ pg_result_check(rb_pgresult);
1525
+ return rb_pgresult;
1526
+ }
1527
+
1528
+
1529
+ /*
1530
+ * call-seq:
1531
+ * conn.make_empty_pgresult( status ) -> PG::Result
1532
+ *
1533
+ * Constructs and empty PG::Result with status _status_.
1534
+ * _status_ may be one of:
1535
+ * * +PGRES_EMPTY_QUERY+
1536
+ * * +PGRES_COMMAND_OK+
1537
+ * * +PGRES_TUPLES_OK+
1538
+ * * +PGRES_COPY_OUT+
1539
+ * * +PGRES_COPY_IN+
1540
+ * * +PGRES_BAD_RESPONSE+
1541
+ * * +PGRES_NONFATAL_ERROR+
1542
+ * * +PGRES_FATAL_ERROR+
1543
+ * * +PGRES_COPY_BOTH+
1544
+ */
1545
+ static VALUE
1546
+ pgconn_make_empty_pgresult(VALUE self, VALUE status)
1547
+ {
1548
+ PGresult *result;
1549
+ VALUE rb_pgresult;
1550
+ PGconn *conn = pg_get_pgconn(self);
1551
+ result = PQmakeEmptyPGresult(conn, NUM2INT(status));
1552
+ rb_pgresult = pg_new_result(result, self);
1553
+ pg_result_check(rb_pgresult);
1554
+ return rb_pgresult;
1555
+ }
1556
+
1557
+
1558
+ /*
1559
+ * call-seq:
1560
+ * conn.escape_string( str ) -> String
1561
+ *
1562
+ * Returns a SQL-safe version of the String _str_.
1563
+ * This is the preferred way to make strings safe for inclusion in
1564
+ * SQL queries.
1565
+ *
1566
+ * Consider using exec_params, which avoids the need for passing values
1567
+ * inside of SQL commands.
1568
+ *
1569
+ * Encoding of escaped string will be equal to client encoding of connection.
1570
+ *
1571
+ * NOTE: This class version of this method can only be used safely in client
1572
+ * programs that use a single PostgreSQL connection at a time (in this case it can
1573
+ * find out what it needs to know "behind the scenes"). It might give the wrong
1574
+ * results if used in programs that use multiple database connections; use the
1575
+ * same method on the connection object in such cases.
1576
+ */
1577
+ static VALUE
1578
+ pgconn_s_escape(VALUE self, VALUE string)
1579
+ {
1580
+ size_t size;
1581
+ int error;
1582
+ VALUE result;
1583
+ int enc_idx;
1584
+ int singleton = !rb_obj_is_kind_of(self, rb_cPGconn);
1585
+
1586
+ StringValueCStr(string);
1587
+ enc_idx = ENCODING_GET( singleton ? string : self );
1588
+ if( ENCODING_GET(string) != enc_idx ){
1589
+ string = rb_str_export_to_enc(string, rb_enc_from_index(enc_idx));
1590
+ }
1591
+
1592
+ result = rb_str_new(NULL, RSTRING_LEN(string) * 2 + 1);
1593
+ PG_ENCODING_SET_NOCHECK(result, enc_idx);
1594
+ if( !singleton ) {
1595
+ size = PQescapeStringConn(pg_get_pgconn(self), RSTRING_PTR(result),
1596
+ RSTRING_PTR(string), RSTRING_LEN(string), &error);
1597
+ if(error) {
1598
+ rb_raise(rb_ePGerror, "%s", PQerrorMessage(pg_get_pgconn(self)));
1599
+ }
1600
+ } else {
1601
+ size = PQescapeString(RSTRING_PTR(result), RSTRING_PTR(string), RSTRING_LEN(string));
1602
+ }
1603
+ rb_str_set_len(result, size);
1604
+ OBJ_INFECT(result, string);
1605
+
1606
+ return result;
1607
+ }
1608
+
1609
+ /*
1610
+ * call-seq:
1611
+ * conn.escape_bytea( string ) -> String
1612
+ *
1613
+ * Escapes binary data for use within an SQL command with the type +bytea+.
1614
+ *
1615
+ * Certain byte values must be escaped (but all byte values may be escaped)
1616
+ * when used as part of a +bytea+ literal in an SQL statement. In general, to
1617
+ * escape a byte, it is converted into the three digit octal number equal to
1618
+ * the octet value, and preceded by two backslashes. The single quote (') and
1619
+ * backslash (\) characters have special alternative escape sequences.
1620
+ * #escape_bytea performs this operation, escaping only the minimally required
1621
+ * bytes.
1622
+ *
1623
+ * Consider using exec_params, which avoids the need for passing values inside of
1624
+ * SQL commands.
1625
+ *
1626
+ * NOTE: This class version of this method can only be used safely in client
1627
+ * programs that use a single PostgreSQL connection at a time (in this case it can
1628
+ * find out what it needs to know "behind the scenes"). It might give the wrong
1629
+ * results if used in programs that use multiple database connections; use the
1630
+ * same method on the connection object in such cases.
1631
+ */
1632
+ static VALUE
1633
+ pgconn_s_escape_bytea(VALUE self, VALUE str)
1634
+ {
1635
+ unsigned char *from, *to;
1636
+ size_t from_len, to_len;
1637
+ VALUE ret;
1638
+
1639
+ Check_Type(str, T_STRING);
1640
+ from = (unsigned char*)RSTRING_PTR(str);
1641
+ from_len = RSTRING_LEN(str);
1642
+
1643
+ if ( rb_obj_is_kind_of(self, rb_cPGconn) ) {
1644
+ to = PQescapeByteaConn(pg_get_pgconn(self), from, from_len, &to_len);
1645
+ } else {
1646
+ to = PQescapeBytea( from, from_len, &to_len);
1647
+ }
1648
+
1649
+ ret = rb_str_new((char*)to, to_len - 1);
1650
+ OBJ_INFECT(ret, str);
1651
+ PQfreemem(to);
1652
+ return ret;
1653
+ }
1654
+
1655
+
1656
+ /*
1657
+ * call-seq:
1658
+ * PG::Connection.unescape_bytea( string )
1659
+ *
1660
+ * Converts an escaped string representation of binary data into binary data --- the
1661
+ * reverse of #escape_bytea. This is needed when retrieving +bytea+ data in text format,
1662
+ * but not when retrieving it in binary format.
1663
+ *
1664
+ */
1665
+ static VALUE
1666
+ pgconn_s_unescape_bytea(VALUE self, VALUE str)
1667
+ {
1668
+ unsigned char *from, *to;
1669
+ size_t to_len;
1670
+ VALUE ret;
1671
+
1672
+ UNUSED( self );
1673
+
1674
+ Check_Type(str, T_STRING);
1675
+ from = (unsigned char*)StringValueCStr(str);
1676
+
1677
+ to = PQunescapeBytea(from, &to_len);
1678
+
1679
+ ret = rb_str_new((char*)to, to_len);
1680
+ OBJ_INFECT(ret, str);
1681
+ PQfreemem(to);
1682
+ return ret;
1683
+ }
1684
+
1685
+ /*
1686
+ * call-seq:
1687
+ * conn.escape_literal( str ) -> String
1688
+ *
1689
+ * Escape an arbitrary String +str+ as a literal.
1690
+ *
1691
+ * Available since PostgreSQL-9.0
1692
+ */
1693
+ static VALUE
1694
+ pgconn_escape_literal(VALUE self, VALUE string)
1695
+ {
1696
+ PGconn *conn = pg_get_pgconn(self);
1697
+ char *escaped = NULL;
1698
+ VALUE error;
1699
+ VALUE result = Qnil;
1700
+ int enc_idx = ENCODING_GET(self);
1701
+
1702
+ StringValueCStr(string);
1703
+ if( ENCODING_GET(string) != enc_idx ){
1704
+ string = rb_str_export_to_enc(string, rb_enc_from_index(enc_idx));
1705
+ }
1706
+
1707
+ escaped = PQescapeLiteral(conn, RSTRING_PTR(string), RSTRING_LEN(string));
1708
+ if (escaped == NULL)
1709
+ {
1710
+ error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn));
1711
+ rb_iv_set(error, "@connection", self);
1712
+ rb_exc_raise(error);
1713
+ return Qnil;
1714
+ }
1715
+ result = rb_str_new2(escaped);
1716
+ PQfreemem(escaped);
1717
+ OBJ_INFECT(result, string);
1718
+ PG_ENCODING_SET_NOCHECK(result, enc_idx);
1719
+
1720
+ return result;
1721
+ }
1722
+
1723
+ /*
1724
+ * call-seq:
1725
+ * conn.escape_identifier( str ) -> String
1726
+ *
1727
+ * Escape an arbitrary String +str+ as an identifier.
1728
+ *
1729
+ * This method does the same as #quote_ident with a String argument,
1730
+ * but it doesn't support an Array argument and it makes use of libpq
1731
+ * to process the string.
1732
+ *
1733
+ * Available since PostgreSQL-9.0
1734
+ */
1735
+ static VALUE
1736
+ pgconn_escape_identifier(VALUE self, VALUE string)
1737
+ {
1738
+ PGconn *conn = pg_get_pgconn(self);
1739
+ char *escaped = NULL;
1740
+ VALUE error;
1741
+ VALUE result = Qnil;
1742
+ int enc_idx = ENCODING_GET(self);
1743
+
1744
+ StringValueCStr(string);
1745
+ if( ENCODING_GET(string) != enc_idx ){
1746
+ string = rb_str_export_to_enc(string, rb_enc_from_index(enc_idx));
1747
+ }
1748
+
1749
+ escaped = PQescapeIdentifier(conn, RSTRING_PTR(string), RSTRING_LEN(string));
1750
+ if (escaped == NULL)
1751
+ {
1752
+ error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn));
1753
+ rb_iv_set(error, "@connection", self);
1754
+ rb_exc_raise(error);
1755
+ return Qnil;
1756
+ }
1757
+ result = rb_str_new2(escaped);
1758
+ PQfreemem(escaped);
1759
+ OBJ_INFECT(result, string);
1760
+ PG_ENCODING_SET_NOCHECK(result, enc_idx);
1761
+
1762
+ return result;
1763
+ }
1764
+
1765
+ /*
1766
+ * call-seq:
1767
+ * conn.set_single_row_mode -> self
1768
+ *
1769
+ * To enter single-row mode, call this method immediately after a successful
1770
+ * call of send_query (or a sibling function). This mode selection is effective
1771
+ * only for the currently executing query.
1772
+ * Then call Connection#get_result repeatedly, until it returns nil.
1773
+ *
1774
+ * Each (but the last) received Result has exactly one row and a
1775
+ * Result#result_status of PGRES_SINGLE_TUPLE. The last Result has
1776
+ * zero rows and is used to indicate a successful execution of the query.
1777
+ * All of these Result objects will contain the same row description data
1778
+ * (column names, types, etc) that an ordinary Result object for the query
1779
+ * would have.
1780
+ *
1781
+ * *Caution:* While processing a query, the server may return some rows and
1782
+ * then encounter an error, causing the query to be aborted. Ordinarily, pg
1783
+ * discards any such rows and reports only the error. But in single-row mode,
1784
+ * those rows will have already been returned to the application. Hence, the
1785
+ * application will see some Result objects followed by an Error raised in get_result.
1786
+ * For proper transactional behavior, the application must be designed to discard
1787
+ * or undo whatever has been done with the previously-processed rows, if the query
1788
+ * ultimately fails.
1789
+ *
1790
+ * Example:
1791
+ * conn.send_query( "your SQL command" )
1792
+ * conn.set_single_row_mode
1793
+ * loop do
1794
+ * res = conn.get_result or break
1795
+ * res.check
1796
+ * res.each do |row|
1797
+ * # do something with the received row
1798
+ * end
1799
+ * end
1800
+ *
1801
+ * Available since PostgreSQL-9.2
1802
+ */
1803
+ static VALUE
1804
+ pgconn_set_single_row_mode(VALUE self)
1805
+ {
1806
+ PGconn *conn = pg_get_pgconn(self);
1807
+ VALUE error;
1808
+
1809
+ if( PQsetSingleRowMode(conn) == 0 )
1810
+ {
1811
+ error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn));
1812
+ rb_iv_set(error, "@connection", self);
1813
+ rb_exc_raise(error);
1814
+ }
1815
+
1816
+ return self;
1817
+ }
1818
+
1819
+ static VALUE pgconn_send_query_params(int argc, VALUE *argv, VALUE self);
1820
+
1821
+ /*
1822
+ * call-seq:
1823
+ * conn.send_query(sql) -> nil
1824
+ *
1825
+ * Sends SQL query request specified by _sql_ to PostgreSQL for
1826
+ * asynchronous processing, and immediately returns.
1827
+ * On failure, it raises a PG::Error.
1828
+ *
1829
+ * For backward compatibility, if you pass more than one parameter to this method,
1830
+ * it will call #send_query_params for you. New code should explicitly use #send_query_params if
1831
+ * argument placeholders are used.
1832
+ *
1833
+ */
1834
+ static VALUE
1835
+ pgconn_send_query(int argc, VALUE *argv, VALUE self)
1836
+ {
1837
+ PGconn *conn = pg_get_pgconn(self);
1838
+ VALUE error;
1839
+
1840
+ /* If called with no or nil parameters, use PQexec for compatibility */
1841
+ if ( argc == 1 || (argc >= 2 && argc <= 4 && NIL_P(argv[1]) )) {
1842
+ if(gvl_PQsendQuery(conn, pg_cstr_enc(argv[0], ENCODING_GET(self))) == 0) {
1843
+ error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn));
1844
+ rb_iv_set(error, "@connection", self);
1845
+ rb_exc_raise(error);
1846
+ }
1847
+ return Qnil;
1848
+ }
1849
+
1850
+ pg_deprecated(2, ("forwarding async_exec to async_exec_params and send_query to send_query_params is deprecated"));
1851
+
1852
+ /* If called with parameters, and optionally result_format,
1853
+ * use PQsendQueryParams
1854
+ */
1855
+ return pgconn_send_query_params( argc, argv, self);
1856
+ }
1857
+
1858
+ /*
1859
+ * call-seq:
1860
+ * conn.send_query_params(sql, params [, result_format [, type_map ]] ) -> nil
1861
+ *
1862
+ * Sends SQL query request specified by _sql_ to PostgreSQL for
1863
+ * asynchronous processing, and immediately returns.
1864
+ * On failure, it raises a PG::Error.
1865
+ *
1866
+ * +params+ is an array of the bind parameters for the SQL query.
1867
+ * Each element of the +params+ array may be either:
1868
+ * a hash of the form:
1869
+ * {:value => String (value of bind parameter)
1870
+ * :type => Integer (oid of type of bind parameter)
1871
+ * :format => Integer (0 for text, 1 for binary)
1872
+ * }
1873
+ * or, it may be a String. If it is a string, that is equivalent to the hash:
1874
+ * { :value => <string value>, :type => 0, :format => 0 }
1875
+ *
1876
+ * PostgreSQL bind parameters are represented as $1, $1, $2, etc.,
1877
+ * inside the SQL query. The 0th element of the +params+ array is bound
1878
+ * to $1, the 1st element is bound to $2, etc. +nil+ is treated as +NULL+.
1879
+ *
1880
+ * If the types are not specified, they will be inferred by PostgreSQL.
1881
+ * Instead of specifying type oids, it's recommended to simply add
1882
+ * explicit casts in the query to ensure that the right type is used.
1883
+ *
1884
+ * For example: "SELECT $1::int"
1885
+ *
1886
+ * The optional +result_format+ should be 0 for text results, 1
1887
+ * for binary.
1888
+ *
1889
+ * type_map can be a PG::TypeMap derivation (such as PG::BasicTypeMapForQueries).
1890
+ * This will type cast the params from various Ruby types before transmission
1891
+ * based on the encoders defined by the type map. When a type encoder is used
1892
+ * the format and oid of a given bind parameter are retrieved from the encoder
1893
+ * instead out of the hash form described above.
1894
+ *
1895
+ */
1896
+ static VALUE
1897
+ pgconn_send_query_params(int argc, VALUE *argv, VALUE self)
1898
+ {
1899
+ PGconn *conn = pg_get_pgconn(self);
1900
+ int result;
1901
+ VALUE command, in_res_fmt;
1902
+ VALUE error;
1903
+ int nParams;
1904
+ int resultFormat;
1905
+ struct query_params_data paramsData = { ENCODING_GET(self) };
1906
+
1907
+ rb_scan_args(argc, argv, "22", &command, &paramsData.params, &in_res_fmt, &paramsData.typemap);
1908
+ paramsData.with_types = 1;
1909
+
1910
+ pgconn_query_assign_typemap( self, &paramsData );
1911
+ resultFormat = NIL_P(in_res_fmt) ? 0 : NUM2INT(in_res_fmt);
1912
+ nParams = alloc_query_params( &paramsData );
1913
+
1914
+ result = gvl_PQsendQueryParams(conn, pg_cstr_enc(command, paramsData.enc_idx), nParams, paramsData.types,
1915
+ (const char * const *)paramsData.values, paramsData.lengths, paramsData.formats, resultFormat);
1916
+
1917
+ free_query_params( &paramsData );
1918
+
1919
+ if(result == 0) {
1920
+ error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn));
1921
+ rb_iv_set(error, "@connection", self);
1922
+ rb_exc_raise(error);
1923
+ }
1924
+ return Qnil;
1925
+ }
1926
+
1927
+ /*
1928
+ * call-seq:
1929
+ * conn.send_prepare( stmt_name, sql [, param_types ] ) -> nil
1930
+ *
1931
+ * Prepares statement _sql_ with name _name_ to be executed later.
1932
+ * Sends prepare command asynchronously, and returns immediately.
1933
+ * On failure, it raises a PG::Error.
1934
+ *
1935
+ * +param_types+ is an optional parameter to specify the Oids of the
1936
+ * types of the parameters.
1937
+ *
1938
+ * If the types are not specified, they will be inferred by PostgreSQL.
1939
+ * Instead of specifying type oids, it's recommended to simply add
1940
+ * explicit casts in the query to ensure that the right type is used.
1941
+ *
1942
+ * For example: "SELECT $1::int"
1943
+ *
1944
+ * PostgreSQL bind parameters are represented as $1, $1, $2, etc.,
1945
+ * inside the SQL query.
1946
+ */
1947
+ static VALUE
1948
+ pgconn_send_prepare(int argc, VALUE *argv, VALUE self)
1949
+ {
1950
+ PGconn *conn = pg_get_pgconn(self);
1951
+ int result;
1952
+ VALUE name, command, in_paramtypes;
1953
+ VALUE param;
1954
+ VALUE error;
1955
+ int i = 0;
1956
+ int nParams = 0;
1957
+ Oid *paramTypes = NULL;
1958
+ const char *name_cstr;
1959
+ const char *command_cstr;
1960
+ int enc_idx = ENCODING_GET(self);
1961
+
1962
+ rb_scan_args(argc, argv, "21", &name, &command, &in_paramtypes);
1963
+ name_cstr = pg_cstr_enc(name, enc_idx);
1964
+ command_cstr = pg_cstr_enc(command, enc_idx);
1965
+
1966
+ if(! NIL_P(in_paramtypes)) {
1967
+ Check_Type(in_paramtypes, T_ARRAY);
1968
+ nParams = (int)RARRAY_LEN(in_paramtypes);
1969
+ paramTypes = ALLOC_N(Oid, nParams);
1970
+ for(i = 0; i < nParams; i++) {
1971
+ param = rb_ary_entry(in_paramtypes, i);
1972
+ if(param == Qnil)
1973
+ paramTypes[i] = 0;
1974
+ else
1975
+ paramTypes[i] = NUM2UINT(param);
1976
+ }
1977
+ }
1978
+ result = gvl_PQsendPrepare(conn, name_cstr, command_cstr, nParams, paramTypes);
1979
+
1980
+ xfree(paramTypes);
1981
+
1982
+ if(result == 0) {
1983
+ error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn));
1984
+ rb_iv_set(error, "@connection", self);
1985
+ rb_exc_raise(error);
1986
+ }
1987
+ return Qnil;
1988
+ }
1989
+
1990
+ /*
1991
+ * call-seq:
1992
+ * conn.send_query_prepared( statement_name [, params, result_format[, type_map ]] )
1993
+ * -> nil
1994
+ *
1995
+ * Execute prepared named statement specified by _statement_name_
1996
+ * asynchronously, and returns immediately.
1997
+ * On failure, it raises a PG::Error.
1998
+ *
1999
+ * +params+ is an array of the optional bind parameters for the
2000
+ * SQL query. Each element of the +params+ array may be either:
2001
+ * a hash of the form:
2002
+ * {:value => String (value of bind parameter)
2003
+ * :format => Integer (0 for text, 1 for binary)
2004
+ * }
2005
+ * or, it may be a String. If it is a string, that is equivalent to the hash:
2006
+ * { :value => <string value>, :format => 0 }
2007
+ *
2008
+ * PostgreSQL bind parameters are represented as $1, $1, $2, etc.,
2009
+ * inside the SQL query. The 0th element of the +params+ array is bound
2010
+ * to $1, the 1st element is bound to $2, etc. +nil+ is treated as +NULL+.
2011
+ *
2012
+ * The optional +result_format+ should be 0 for text results, 1
2013
+ * for binary.
2014
+ *
2015
+ * type_map can be a PG::TypeMap derivation (such as PG::BasicTypeMapForQueries).
2016
+ * This will type cast the params from various Ruby types before transmission
2017
+ * based on the encoders defined by the type map. When a type encoder is used
2018
+ * the format and oid of a given bind parameter are retrieved from the encoder
2019
+ * instead out of the hash form described above.
2020
+ *
2021
+ */
2022
+ static VALUE
2023
+ pgconn_send_query_prepared(int argc, VALUE *argv, VALUE self)
2024
+ {
2025
+ PGconn *conn = pg_get_pgconn(self);
2026
+ int result;
2027
+ VALUE name, in_res_fmt;
2028
+ VALUE error;
2029
+ int nParams;
2030
+ int resultFormat;
2031
+ struct query_params_data paramsData = { ENCODING_GET(self) };
2032
+
2033
+ rb_scan_args(argc, argv, "13", &name, &paramsData.params, &in_res_fmt, &paramsData.typemap);
2034
+ paramsData.with_types = 0;
2035
+
2036
+ if(NIL_P(paramsData.params)) {
2037
+ paramsData.params = rb_ary_new2(0);
2038
+ resultFormat = 0;
2039
+ }
2040
+ pgconn_query_assign_typemap( self, &paramsData );
2041
+
2042
+ resultFormat = NIL_P(in_res_fmt) ? 0 : NUM2INT(in_res_fmt);
2043
+ nParams = alloc_query_params( &paramsData );
2044
+
2045
+ result = gvl_PQsendQueryPrepared(conn, pg_cstr_enc(name, paramsData.enc_idx), nParams,
2046
+ (const char * const *)paramsData.values, paramsData.lengths, paramsData.formats,
2047
+ resultFormat);
2048
+
2049
+ free_query_params( &paramsData );
2050
+
2051
+ if(result == 0) {
2052
+ error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn));
2053
+ rb_iv_set(error, "@connection", self);
2054
+ rb_exc_raise(error);
2055
+ }
2056
+ return Qnil;
2057
+ }
2058
+
2059
+ /*
2060
+ * call-seq:
2061
+ * conn.send_describe_prepared( statement_name ) -> nil
2062
+ *
2063
+ * Asynchronously send _command_ to the server. Does not block.
2064
+ * Use in combination with +conn.get_result+.
2065
+ */
2066
+ static VALUE
2067
+ pgconn_send_describe_prepared(VALUE self, VALUE stmt_name)
2068
+ {
2069
+ VALUE error;
2070
+ PGconn *conn = pg_get_pgconn(self);
2071
+ /* returns 0 on failure */
2072
+ if(gvl_PQsendDescribePrepared(conn, pg_cstr_enc(stmt_name, ENCODING_GET(self))) == 0) {
2073
+ error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn));
2074
+ rb_iv_set(error, "@connection", self);
2075
+ rb_exc_raise(error);
2076
+ }
2077
+ return Qnil;
2078
+ }
2079
+
2080
+
2081
+ /*
2082
+ * call-seq:
2083
+ * conn.send_describe_portal( portal_name ) -> nil
2084
+ *
2085
+ * Asynchronously send _command_ to the server. Does not block.
2086
+ * Use in combination with +conn.get_result+.
2087
+ */
2088
+ static VALUE
2089
+ pgconn_send_describe_portal(VALUE self, VALUE portal)
2090
+ {
2091
+ VALUE error;
2092
+ PGconn *conn = pg_get_pgconn(self);
2093
+ /* returns 0 on failure */
2094
+ if(gvl_PQsendDescribePortal(conn, pg_cstr_enc(portal, ENCODING_GET(self))) == 0) {
2095
+ error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn));
2096
+ rb_iv_set(error, "@connection", self);
2097
+ rb_exc_raise(error);
2098
+ }
2099
+ return Qnil;
2100
+ }
2101
+
2102
+
2103
+ /*
2104
+ * call-seq:
2105
+ * conn.get_result() -> PG::Result
2106
+ * conn.get_result() {|pg_result| block }
2107
+ *
2108
+ * Blocks waiting for the next result from a call to
2109
+ * #send_query (or another asynchronous command), and returns
2110
+ * it. Returns +nil+ if no more results are available.
2111
+ *
2112
+ * Note: call this function repeatedly until it returns +nil+, or else
2113
+ * you will not be able to issue further commands.
2114
+ *
2115
+ * If the optional code block is given, it will be passed <i>result</i> as an argument,
2116
+ * and the PG::Result object will automatically be cleared when the block terminates.
2117
+ * In this instance, <code>conn.exec</code> returns the value of the block.
2118
+ */
2119
+ static VALUE
2120
+ pgconn_get_result(VALUE self)
2121
+ {
2122
+ PGconn *conn = pg_get_pgconn(self);
2123
+ PGresult *result;
2124
+ VALUE rb_pgresult;
2125
+
2126
+ result = gvl_PQgetResult(conn);
2127
+ if(result == NULL)
2128
+ return Qnil;
2129
+ rb_pgresult = pg_new_result(result, self);
2130
+ if (rb_block_given_p()) {
2131
+ return rb_ensure(rb_yield, rb_pgresult,
2132
+ pg_result_clear, rb_pgresult);
2133
+ }
2134
+ return rb_pgresult;
2135
+ }
2136
+
2137
+ /*
2138
+ * call-seq:
2139
+ * conn.consume_input()
2140
+ *
2141
+ * If input is available from the server, consume it.
2142
+ * After calling +consume_input+, you can check +is_busy+
2143
+ * or *notifies* to see if the state has changed.
2144
+ */
2145
+ static VALUE
2146
+ pgconn_consume_input(self)
2147
+ VALUE self;
2148
+ {
2149
+ VALUE error;
2150
+ PGconn *conn = pg_get_pgconn(self);
2151
+ /* returns 0 on error */
2152
+ if(PQconsumeInput(conn) == 0) {
2153
+ error = rb_exc_new2(rb_eConnectionBad, PQerrorMessage(conn));
2154
+ rb_iv_set(error, "@connection", self);
2155
+ rb_exc_raise(error);
2156
+ }
2157
+ return Qnil;
2158
+ }
2159
+
2160
+ /*
2161
+ * call-seq:
2162
+ * conn.is_busy() -> Boolean
2163
+ *
2164
+ * Returns +true+ if a command is busy, that is, if
2165
+ * PQgetResult would block. Otherwise returns +false+.
2166
+ */
2167
+ static VALUE
2168
+ pgconn_is_busy(self)
2169
+ VALUE self;
2170
+ {
2171
+ return gvl_PQisBusy(pg_get_pgconn(self)) ? Qtrue : Qfalse;
2172
+ }
2173
+
2174
+ /*
2175
+ * call-seq:
2176
+ * conn.setnonblocking(Boolean) -> nil
2177
+ *
2178
+ * Sets the nonblocking status of the connection.
2179
+ * In the blocking state, calls to #send_query
2180
+ * will block until the message is sent to the server,
2181
+ * but will not wait for the query results.
2182
+ * In the nonblocking state, calls to #send_query
2183
+ * will return an error if the socket is not ready for
2184
+ * writing.
2185
+ * Note: This function does not affect #exec, because
2186
+ * that function doesn't return until the server has
2187
+ * processed the query and returned the results.
2188
+ * Returns +nil+.
2189
+ */
2190
+ static VALUE
2191
+ pgconn_setnonblocking(self, state)
2192
+ VALUE self, state;
2193
+ {
2194
+ int arg;
2195
+ VALUE error;
2196
+ PGconn *conn = pg_get_pgconn(self);
2197
+ if(state == Qtrue)
2198
+ arg = 1;
2199
+ else if (state == Qfalse)
2200
+ arg = 0;
2201
+ else
2202
+ rb_raise(rb_eArgError, "Boolean value expected");
2203
+
2204
+ if(PQsetnonblocking(conn, arg) == -1) {
2205
+ error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn));
2206
+ rb_iv_set(error, "@connection", self);
2207
+ rb_exc_raise(error);
2208
+ }
2209
+ return Qnil;
2210
+ }
2211
+
2212
+
2213
+ /*
2214
+ * call-seq:
2215
+ * conn.isnonblocking() -> Boolean
2216
+ *
2217
+ * Returns +true+ if a command is busy, that is, if
2218
+ * PQgetResult would block. Otherwise returns +false+.
2219
+ */
2220
+ static VALUE
2221
+ pgconn_isnonblocking(self)
2222
+ VALUE self;
2223
+ {
2224
+ return PQisnonblocking(pg_get_pgconn(self)) ? Qtrue : Qfalse;
2225
+ }
2226
+
2227
+ /*
2228
+ * call-seq:
2229
+ * conn.flush() -> Boolean
2230
+ *
2231
+ * Attempts to flush any queued output data to the server.
2232
+ * Returns +true+ if data is successfully flushed, +false+
2233
+ * if not (can only return +false+ if connection is
2234
+ * nonblocking.
2235
+ * Raises PG::Error if some other failure occurred.
2236
+ */
2237
+ static VALUE
2238
+ pgconn_flush(self)
2239
+ VALUE self;
2240
+ {
2241
+ PGconn *conn = pg_get_pgconn(self);
2242
+ int ret;
2243
+ VALUE error;
2244
+ ret = PQflush(conn);
2245
+ if(ret == -1) {
2246
+ error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn));
2247
+ rb_iv_set(error, "@connection", self);
2248
+ rb_exc_raise(error);
2249
+ }
2250
+ return (ret) ? Qfalse : Qtrue;
2251
+ }
2252
+
2253
+ /*
2254
+ * call-seq:
2255
+ * conn.cancel() -> String
2256
+ *
2257
+ * Requests cancellation of the command currently being
2258
+ * processed. (Only implemented in PostgreSQL >= 8.0)
2259
+ *
2260
+ * Returns +nil+ on success, or a string containing the
2261
+ * error message if a failure occurs.
2262
+ */
2263
+ static VALUE
2264
+ pgconn_cancel(VALUE self)
2265
+ {
2266
+ char errbuf[256];
2267
+ PGcancel *cancel;
2268
+ VALUE retval;
2269
+ int ret;
2270
+
2271
+ cancel = PQgetCancel(pg_get_pgconn(self));
2272
+ if(cancel == NULL)
2273
+ rb_raise(rb_ePGerror,"Invalid connection!");
2274
+
2275
+ ret = gvl_PQcancel(cancel, errbuf, 256);
2276
+ if(ret == 1)
2277
+ retval = Qnil;
2278
+ else
2279
+ retval = rb_str_new2(errbuf);
2280
+
2281
+ PQfreeCancel(cancel);
2282
+ return retval;
2283
+ }
2284
+
2285
+
2286
+ /*
2287
+ * call-seq:
2288
+ * conn.notifies()
2289
+ *
2290
+ * Returns a hash of the unprocessed notifications.
2291
+ * If there is no unprocessed notifier, it returns +nil+.
2292
+ */
2293
+ static VALUE
2294
+ pgconn_notifies(VALUE self)
2295
+ {
2296
+ PGconn* conn = pg_get_pgconn(self);
2297
+ PGnotify *notification;
2298
+ VALUE hash;
2299
+ VALUE sym_relname, sym_be_pid, sym_extra;
2300
+ VALUE relname, be_pid, extra;
2301
+
2302
+ sym_relname = ID2SYM(rb_intern("relname"));
2303
+ sym_be_pid = ID2SYM(rb_intern("be_pid"));
2304
+ sym_extra = ID2SYM(rb_intern("extra"));
2305
+
2306
+ notification = gvl_PQnotifies(conn);
2307
+ if (notification == NULL) {
2308
+ return Qnil;
2309
+ }
2310
+
2311
+ hash = rb_hash_new();
2312
+ relname = rb_tainted_str_new2(notification->relname);
2313
+ be_pid = INT2NUM(notification->be_pid);
2314
+ extra = rb_tainted_str_new2(notification->extra);
2315
+ PG_ENCODING_SET_NOCHECK( relname, ENCODING_GET(self) );
2316
+ PG_ENCODING_SET_NOCHECK( extra, ENCODING_GET(self) );
2317
+
2318
+ rb_hash_aset(hash, sym_relname, relname);
2319
+ rb_hash_aset(hash, sym_be_pid, be_pid);
2320
+ rb_hash_aset(hash, sym_extra, extra);
2321
+
2322
+ PQfreemem(notification);
2323
+ return hash;
2324
+ }
2325
+
2326
+ /* Win32 + Ruby 1.9+ */
2327
+ #if defined( _WIN32 )
2328
+ /*
2329
+ * On Windows, use platform-specific strategies to wait for the socket
2330
+ * instead of rb_wait_for_single_fd().
2331
+ */
2332
+
2333
+ int rb_w32_wait_events( HANDLE *events, int num, DWORD timeout );
2334
+
2335
+ static void *
2336
+ wait_socket_readable( PGconn *conn, struct timeval *ptimeout, void *(*is_readable)(PGconn *) )
2337
+ {
2338
+ int sd = PQsocket( conn );
2339
+ void *retval;
2340
+ struct timeval aborttime={0,0}, currtime, waittime;
2341
+ DWORD timeout_milisec = INFINITE;
2342
+ DWORD wait_ret;
2343
+ WSAEVENT hEvent;
2344
+
2345
+ if ( sd < 0 )
2346
+ rb_raise(rb_eConnectionBad, "PQsocket() can't get socket descriptor");
2347
+
2348
+ hEvent = WSACreateEvent();
2349
+
2350
+ /* Check for connection errors (PQisBusy is true on connection errors) */
2351
+ if( PQconsumeInput(conn) == 0 ) {
2352
+ WSACloseEvent( hEvent );
2353
+ rb_raise( rb_eConnectionBad, "PQconsumeInput() %s", PQerrorMessage(conn) );
2354
+ }
2355
+
2356
+ if ( ptimeout ) {
2357
+ gettimeofday(&currtime, NULL);
2358
+ timeradd(&currtime, ptimeout, &aborttime);
2359
+ }
2360
+
2361
+ while ( !(retval=is_readable(conn)) ) {
2362
+ if ( WSAEventSelect(sd, hEvent, FD_READ|FD_CLOSE) == SOCKET_ERROR ) {
2363
+ WSACloseEvent( hEvent );
2364
+ rb_raise( rb_eConnectionBad, "WSAEventSelect socket error: %d", WSAGetLastError() );
2365
+ }
2366
+
2367
+ if ( ptimeout ) {
2368
+ gettimeofday(&currtime, NULL);
2369
+ timersub(&aborttime, &currtime, &waittime);
2370
+ timeout_milisec = (DWORD)( waittime.tv_sec * 1e3 + waittime.tv_usec / 1e3 );
2371
+ }
2372
+
2373
+ /* Is the given timeout valid? */
2374
+ if( !ptimeout || (waittime.tv_sec >= 0 && waittime.tv_usec >= 0) ){
2375
+ /* Wait for the socket to become readable before checking again */
2376
+ wait_ret = rb_w32_wait_events( &hEvent, 1, timeout_milisec );
2377
+ } else {
2378
+ wait_ret = WAIT_TIMEOUT;
2379
+ }
2380
+
2381
+ if ( wait_ret == WAIT_TIMEOUT ) {
2382
+ WSACloseEvent( hEvent );
2383
+ return NULL;
2384
+ } else if ( wait_ret == WAIT_OBJECT_0 ) {
2385
+ /* The event we were waiting for. */
2386
+ } else if ( wait_ret == WAIT_OBJECT_0 + 1) {
2387
+ /* This indicates interruption from timer thread, GC, exception
2388
+ * from other threads etc... */
2389
+ rb_thread_check_ints();
2390
+ } else if ( wait_ret == WAIT_FAILED ) {
2391
+ WSACloseEvent( hEvent );
2392
+ rb_raise( rb_eConnectionBad, "Wait on socket error (WaitForMultipleObjects): %lu", GetLastError() );
2393
+ } else {
2394
+ WSACloseEvent( hEvent );
2395
+ rb_raise( rb_eConnectionBad, "Wait on socket abandoned (WaitForMultipleObjects)" );
2396
+ }
2397
+
2398
+ /* Check for connection errors (PQisBusy is true on connection errors) */
2399
+ if ( PQconsumeInput(conn) == 0 ) {
2400
+ WSACloseEvent( hEvent );
2401
+ rb_raise( rb_eConnectionBad, "PQconsumeInput() %s", PQerrorMessage(conn) );
2402
+ }
2403
+ }
2404
+
2405
+ WSACloseEvent( hEvent );
2406
+ return retval;
2407
+ }
2408
+
2409
+ #else
2410
+
2411
+ /* non Win32 */
2412
+
2413
+ static void *
2414
+ wait_socket_readable( PGconn *conn, struct timeval *ptimeout, void *(*is_readable)(PGconn *))
2415
+ {
2416
+ int sd = PQsocket( conn );
2417
+ int ret;
2418
+ void *retval;
2419
+ struct timeval aborttime={0,0}, currtime, waittime;
2420
+
2421
+ if ( sd < 0 )
2422
+ rb_raise(rb_eConnectionBad, "PQsocket() can't get socket descriptor");
2423
+
2424
+ /* Check for connection errors (PQisBusy is true on connection errors) */
2425
+ if ( PQconsumeInput(conn) == 0 )
2426
+ rb_raise( rb_eConnectionBad, "PQconsumeInput() %s", PQerrorMessage(conn) );
2427
+
2428
+ if ( ptimeout ) {
2429
+ gettimeofday(&currtime, NULL);
2430
+ timeradd(&currtime, ptimeout, &aborttime);
2431
+ }
2432
+
2433
+ while ( !(retval=is_readable(conn)) ) {
2434
+ if ( ptimeout ) {
2435
+ gettimeofday(&currtime, NULL);
2436
+ timersub(&aborttime, &currtime, &waittime);
2437
+ }
2438
+
2439
+ /* Is the given timeout valid? */
2440
+ if( !ptimeout || (waittime.tv_sec >= 0 && waittime.tv_usec >= 0) ){
2441
+ /* Wait for the socket to become readable before checking again */
2442
+ ret = rb_wait_for_single_fd( sd, RB_WAITFD_IN, ptimeout ? &waittime : NULL );
2443
+ } else {
2444
+ ret = 0;
2445
+ }
2446
+
2447
+ if ( ret < 0 ){
2448
+ rb_sys_fail( "rb_wait_for_single_fd()" );
2449
+ }
2450
+
2451
+ /* Return false if the select() timed out */
2452
+ if ( ret == 0 ){
2453
+ return NULL;
2454
+ }
2455
+
2456
+ /* Check for connection errors (PQisBusy is true on connection errors) */
2457
+ if ( PQconsumeInput(conn) == 0 ){
2458
+ rb_raise( rb_eConnectionBad, "PQconsumeInput() %s", PQerrorMessage(conn) );
2459
+ }
2460
+ }
2461
+
2462
+ return retval;
2463
+ }
2464
+
2465
+
2466
+ #endif
2467
+
2468
+ static void *
2469
+ notify_readable(PGconn *conn)
2470
+ {
2471
+ return (void*)gvl_PQnotifies(conn);
2472
+ }
2473
+
2474
+ /*
2475
+ * call-seq:
2476
+ * conn.wait_for_notify( [ timeout ] ) { |event, pid, payload| block } -> String
2477
+ *
2478
+ * Blocks while waiting for notification(s), or until the optional
2479
+ * _timeout_ is reached, whichever comes first. _timeout_ is
2480
+ * measured in seconds and can be fractional.
2481
+ *
2482
+ * Returns +nil+ if _timeout_ is reached, the name of the NOTIFY event otherwise.
2483
+ * If used in block form, passes the name of the NOTIFY +event+, the generating
2484
+ * +pid+ and the optional +payload+ string into the block.
2485
+ */
2486
+ static VALUE
2487
+ pgconn_wait_for_notify(int argc, VALUE *argv, VALUE self)
2488
+ {
2489
+ PGconn *conn = pg_get_pgconn( self );
2490
+ PGnotify *pnotification;
2491
+ struct timeval timeout;
2492
+ struct timeval *ptimeout = NULL;
2493
+ VALUE timeout_in = Qnil, relname = Qnil, be_pid = Qnil, extra = Qnil;
2494
+ double timeout_sec;
2495
+
2496
+ rb_scan_args( argc, argv, "01", &timeout_in );
2497
+
2498
+ if ( RTEST(timeout_in) ) {
2499
+ timeout_sec = NUM2DBL( timeout_in );
2500
+ timeout.tv_sec = (time_t)timeout_sec;
2501
+ timeout.tv_usec = (suseconds_t)( (timeout_sec - (long)timeout_sec) * 1e6 );
2502
+ ptimeout = &timeout;
2503
+ }
2504
+
2505
+ pnotification = (PGnotify*) wait_socket_readable( conn, ptimeout, notify_readable);
2506
+
2507
+ /* Return nil if the select timed out */
2508
+ if ( !pnotification ) return Qnil;
2509
+
2510
+ relname = rb_tainted_str_new2( pnotification->relname );
2511
+ PG_ENCODING_SET_NOCHECK( relname, ENCODING_GET(self) );
2512
+ be_pid = INT2NUM( pnotification->be_pid );
2513
+ if ( *pnotification->extra ) {
2514
+ extra = rb_tainted_str_new2( pnotification->extra );
2515
+ PG_ENCODING_SET_NOCHECK( extra, ENCODING_GET(self) );
2516
+ }
2517
+ PQfreemem( pnotification );
2518
+
2519
+ if ( rb_block_given_p() )
2520
+ rb_yield_values( 3, relname, be_pid, extra );
2521
+
2522
+ return relname;
2523
+ }
2524
+
2525
+
2526
+ /*
2527
+ * call-seq:
2528
+ * conn.put_copy_data( buffer [, encoder] ) -> Boolean
2529
+ *
2530
+ * Transmits _buffer_ as copy data to the server.
2531
+ * Returns true if the data was sent, false if it was
2532
+ * not sent (false is only possible if the connection
2533
+ * is in nonblocking mode, and this command would block).
2534
+ *
2535
+ * _encoder_ can be a PG::Coder derivation (typically PG::TextEncoder::CopyRow).
2536
+ * This encodes the data fields given as _buffer_ from an Array of Strings to
2537
+ * PostgreSQL's COPY text format inclusive proper escaping. Optionally
2538
+ * the encoder can type cast the fields from various Ruby types in one step,
2539
+ * if PG::TextEncoder::CopyRow#type_map is set accordingly.
2540
+ *
2541
+ * Raises an exception if an error occurs.
2542
+ *
2543
+ * See also #copy_data.
2544
+ *
2545
+ */
2546
+ static VALUE
2547
+ pgconn_put_copy_data(int argc, VALUE *argv, VALUE self)
2548
+ {
2549
+ int ret;
2550
+ int len;
2551
+ t_pg_connection *this = pg_get_connection_safe( self );
2552
+ VALUE value;
2553
+ VALUE buffer = Qnil;
2554
+ VALUE encoder;
2555
+ VALUE intermediate;
2556
+ t_pg_coder *p_coder = NULL;
2557
+
2558
+ rb_scan_args( argc, argv, "11", &value, &encoder );
2559
+
2560
+ if( NIL_P(encoder) ){
2561
+ if( NIL_P(this->encoder_for_put_copy_data) ){
2562
+ buffer = value;
2563
+ } else {
2564
+ p_coder = DATA_PTR( this->encoder_for_put_copy_data );
2565
+ }
2566
+ } else if( rb_obj_is_kind_of(encoder, rb_cPG_Coder) ) {
2567
+ Data_Get_Struct( encoder, t_pg_coder, p_coder );
2568
+ } else {
2569
+ rb_raise( rb_eTypeError, "wrong encoder type %s (expected some kind of PG::Coder)",
2570
+ rb_obj_classname( encoder ) );
2571
+ }
2572
+
2573
+ if( p_coder ){
2574
+ t_pg_coder_enc_func enc_func;
2575
+ int enc_idx = ENCODING_GET(self);
2576
+
2577
+ enc_func = pg_coder_enc_func( p_coder );
2578
+ len = enc_func( p_coder, value, NULL, &intermediate, enc_idx);
2579
+
2580
+ if( len == -1 ){
2581
+ /* The intermediate value is a String that can be used directly. */
2582
+ buffer = intermediate;
2583
+ } else {
2584
+ buffer = rb_str_new(NULL, len);
2585
+ len = enc_func( p_coder, value, RSTRING_PTR(buffer), &intermediate, enc_idx);
2586
+ rb_str_set_len( buffer, len );
2587
+ }
2588
+ }
2589
+
2590
+ Check_Type(buffer, T_STRING);
2591
+
2592
+ ret = gvl_PQputCopyData(this->pgconn, RSTRING_PTR(buffer), RSTRING_LENINT(buffer));
2593
+ if(ret == -1) {
2594
+ VALUE error = rb_exc_new2(rb_ePGerror, PQerrorMessage(this->pgconn));
2595
+ rb_iv_set(error, "@connection", self);
2596
+ rb_exc_raise(error);
2597
+ }
2598
+ RB_GC_GUARD(intermediate);
2599
+ RB_GC_GUARD(buffer);
2600
+
2601
+ return (ret) ? Qtrue : Qfalse;
2602
+ }
2603
+
2604
+ /*
2605
+ * call-seq:
2606
+ * conn.put_copy_end( [ error_message ] ) -> Boolean
2607
+ *
2608
+ * Sends end-of-data indication to the server.
2609
+ *
2610
+ * _error_message_ is an optional parameter, and if set,
2611
+ * forces the COPY command to fail with the string
2612
+ * _error_message_.
2613
+ *
2614
+ * Returns true if the end-of-data was sent, false if it was
2615
+ * not sent (false is only possible if the connection
2616
+ * is in nonblocking mode, and this command would block).
2617
+ */
2618
+ static VALUE
2619
+ pgconn_put_copy_end(int argc, VALUE *argv, VALUE self)
2620
+ {
2621
+ VALUE str;
2622
+ VALUE error;
2623
+ int ret;
2624
+ const char *error_message = NULL;
2625
+ PGconn *conn = pg_get_pgconn(self);
2626
+
2627
+ if (rb_scan_args(argc, argv, "01", &str) == 0)
2628
+ error_message = NULL;
2629
+ else
2630
+ error_message = pg_cstr_enc(str, ENCODING_GET(self));
2631
+
2632
+ ret = gvl_PQputCopyEnd(conn, error_message);
2633
+ if(ret == -1) {
2634
+ error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn));
2635
+ rb_iv_set(error, "@connection", self);
2636
+ rb_exc_raise(error);
2637
+ }
2638
+ return (ret) ? Qtrue : Qfalse;
2639
+ }
2640
+
2641
+ /*
2642
+ * call-seq:
2643
+ * conn.get_copy_data( [ async = false [, decoder = nil ]] ) -> Object
2644
+ *
2645
+ * Return one row of data, +nil+
2646
+ * if the copy is done, or +false+ if the call would
2647
+ * block (only possible if _async_ is true).
2648
+ *
2649
+ * If _decoder_ is not set or +nil+, data is returned as binary string.
2650
+ *
2651
+ * If _decoder_ is set to a PG::Coder derivation, the return type depends on this decoder.
2652
+ * PG::TextDecoder::CopyRow decodes the received data fields from one row of PostgreSQL's
2653
+ * COPY text format to an Array of Strings.
2654
+ * Optionally the decoder can type cast the single fields to various Ruby types in one step,
2655
+ * if PG::TextDecoder::CopyRow#type_map is set accordingly.
2656
+ *
2657
+ * See also #copy_data.
2658
+ *
2659
+ */
2660
+ static VALUE
2661
+ pgconn_get_copy_data(int argc, VALUE *argv, VALUE self )
2662
+ {
2663
+ VALUE async_in;
2664
+ VALUE error;
2665
+ VALUE result;
2666
+ int ret;
2667
+ char *buffer;
2668
+ VALUE decoder;
2669
+ t_pg_coder *p_coder = NULL;
2670
+ t_pg_connection *this = pg_get_connection_safe( self );
2671
+
2672
+ rb_scan_args(argc, argv, "02", &async_in, &decoder);
2673
+
2674
+ if( NIL_P(decoder) ){
2675
+ if( !NIL_P(this->decoder_for_get_copy_data) ){
2676
+ p_coder = DATA_PTR( this->decoder_for_get_copy_data );
2677
+ }
2678
+ } else if( rb_obj_is_kind_of(decoder, rb_cPG_Coder) ) {
2679
+ Data_Get_Struct( decoder, t_pg_coder, p_coder );
2680
+ } else {
2681
+ rb_raise( rb_eTypeError, "wrong decoder type %s (expected some kind of PG::Coder)",
2682
+ rb_obj_classname( decoder ) );
2683
+ }
2684
+
2685
+ ret = gvl_PQgetCopyData(this->pgconn, &buffer, RTEST(async_in));
2686
+ if(ret == -2) { /* error */
2687
+ error = rb_exc_new2(rb_ePGerror, PQerrorMessage(this->pgconn));
2688
+ rb_iv_set(error, "@connection", self);
2689
+ rb_exc_raise(error);
2690
+ }
2691
+ if(ret == -1) { /* No data left */
2692
+ return Qnil;
2693
+ }
2694
+ if(ret == 0) { /* would block */
2695
+ return Qfalse;
2696
+ }
2697
+
2698
+ if( p_coder ){
2699
+ t_pg_coder_dec_func dec_func = pg_coder_dec_func( p_coder, p_coder->format );
2700
+ result = dec_func( p_coder, buffer, ret, 0, 0, ENCODING_GET(self) );
2701
+ } else {
2702
+ result = rb_tainted_str_new(buffer, ret);
2703
+ }
2704
+
2705
+ PQfreemem(buffer);
2706
+ return result;
2707
+ }
2708
+
2709
+ /*
2710
+ * call-seq:
2711
+ * conn.set_error_verbosity( verbosity ) -> Integer
2712
+ *
2713
+ * Sets connection's verbosity to _verbosity_ and returns
2714
+ * the previous setting. Available settings are:
2715
+ * * PQERRORS_TERSE
2716
+ * * PQERRORS_DEFAULT
2717
+ * * PQERRORS_VERBOSE
2718
+ */
2719
+ static VALUE
2720
+ pgconn_set_error_verbosity(VALUE self, VALUE in_verbosity)
2721
+ {
2722
+ PGconn *conn = pg_get_pgconn(self);
2723
+ PGVerbosity verbosity = NUM2INT(in_verbosity);
2724
+ return INT2FIX(PQsetErrorVerbosity(conn, verbosity));
2725
+ }
2726
+
2727
+ /*
2728
+ * call-seq:
2729
+ * conn.trace( stream ) -> nil
2730
+ *
2731
+ * Enables tracing message passing between backend. The
2732
+ * trace message will be written to the stream _stream_,
2733
+ * which must implement a method +fileno+ that returns
2734
+ * a writable file descriptor.
2735
+ */
2736
+ static VALUE
2737
+ pgconn_trace(VALUE self, VALUE stream)
2738
+ {
2739
+ VALUE fileno;
2740
+ FILE *new_fp;
2741
+ int old_fd, new_fd;
2742
+ VALUE new_file;
2743
+ t_pg_connection *this = pg_get_connection_safe( self );
2744
+
2745
+ if(rb_respond_to(stream,rb_intern("fileno")) == Qfalse)
2746
+ rb_raise(rb_eArgError, "stream does not respond to method: fileno");
2747
+
2748
+ fileno = rb_funcall(stream, rb_intern("fileno"), 0);
2749
+ if(fileno == Qnil)
2750
+ rb_raise(rb_eArgError, "can't get file descriptor from stream");
2751
+
2752
+ /* Duplicate the file descriptor and re-open
2753
+ * it. Then, make it into a ruby File object
2754
+ * and assign it to an instance variable.
2755
+ * This prevents a problem when the File
2756
+ * object passed to this function is closed
2757
+ * before the connection object is. */
2758
+ old_fd = NUM2INT(fileno);
2759
+ new_fd = dup(old_fd);
2760
+ new_fp = fdopen(new_fd, "w");
2761
+
2762
+ if(new_fp == NULL)
2763
+ rb_raise(rb_eArgError, "stream is not writable");
2764
+
2765
+ new_file = rb_funcall(rb_cIO, rb_intern("new"), 1, INT2NUM(new_fd));
2766
+ this->trace_stream = new_file;
2767
+
2768
+ PQtrace(this->pgconn, new_fp);
2769
+ return Qnil;
2770
+ }
2771
+
2772
+ /*
2773
+ * call-seq:
2774
+ * conn.untrace() -> nil
2775
+ *
2776
+ * Disables the message tracing.
2777
+ */
2778
+ static VALUE
2779
+ pgconn_untrace(VALUE self)
2780
+ {
2781
+ t_pg_connection *this = pg_get_connection_safe( self );
2782
+
2783
+ PQuntrace(this->pgconn);
2784
+ rb_funcall(this->trace_stream, rb_intern("close"), 0);
2785
+ this->trace_stream = Qnil;
2786
+ return Qnil;
2787
+ }
2788
+
2789
+
2790
+ /*
2791
+ * Notice callback proxy function -- delegate the callback to the
2792
+ * currently-registered Ruby notice_receiver object.
2793
+ */
2794
+ void
2795
+ notice_receiver_proxy(void *arg, const PGresult *pgresult)
2796
+ {
2797
+ VALUE self = (VALUE)arg;
2798
+ t_pg_connection *this = pg_get_connection( self );
2799
+
2800
+ if (this->notice_receiver != Qnil) {
2801
+ VALUE result = pg_new_result_autoclear( (PGresult *)pgresult, self );
2802
+
2803
+ rb_funcall(this->notice_receiver, rb_intern("call"), 1, result);
2804
+ pg_result_clear( result );
2805
+ }
2806
+ return;
2807
+ }
2808
+
2809
+ /*
2810
+ * call-seq:
2811
+ * conn.set_notice_receiver {|result| ... } -> Proc
2812
+ *
2813
+ * Notice and warning messages generated by the server are not returned
2814
+ * by the query execution functions, since they do not imply failure of
2815
+ * the query. Instead they are passed to a notice handling function, and
2816
+ * execution continues normally after the handler returns. The default
2817
+ * notice handling function prints the message on <tt>stderr</tt>, but the
2818
+ * application can override this behavior by supplying its own handling
2819
+ * function.
2820
+ *
2821
+ * For historical reasons, there are two levels of notice handling, called the
2822
+ * notice receiver and notice processor. The default behavior is for the notice
2823
+ * receiver to format the notice and pass a string to the notice processor for
2824
+ * printing. However, an application that chooses to provide its own notice
2825
+ * receiver will typically ignore the notice processor layer and just do all
2826
+ * the work in the notice receiver.
2827
+ *
2828
+ * This function takes a new block to act as the handler, which should
2829
+ * accept a single parameter that will be a PG::Result object, and returns
2830
+ * the Proc object previously set, or +nil+ if it was previously the default.
2831
+ *
2832
+ * If you pass no arguments, it will reset the handler to the default.
2833
+ *
2834
+ * *Note:* The +result+ passed to the block should not be used outside
2835
+ * of the block, since the corresponding C object could be freed after the
2836
+ * block finishes.
2837
+ */
2838
+ static VALUE
2839
+ pgconn_set_notice_receiver(VALUE self)
2840
+ {
2841
+ VALUE proc, old_proc;
2842
+ t_pg_connection *this = pg_get_connection_safe( self );
2843
+
2844
+ /* If default_notice_receiver is unset, assume that the current
2845
+ * notice receiver is the default, and save it to a global variable.
2846
+ * This should not be a problem because the default receiver is
2847
+ * always the same, so won't vary among connections.
2848
+ */
2849
+ if(default_notice_receiver == NULL)
2850
+ default_notice_receiver = PQsetNoticeReceiver(this->pgconn, NULL, NULL);
2851
+
2852
+ old_proc = this->notice_receiver;
2853
+ if( rb_block_given_p() ) {
2854
+ proc = rb_block_proc();
2855
+ PQsetNoticeReceiver(this->pgconn, gvl_notice_receiver_proxy, (void *)self);
2856
+ } else {
2857
+ /* if no block is given, set back to default */
2858
+ proc = Qnil;
2859
+ PQsetNoticeReceiver(this->pgconn, default_notice_receiver, NULL);
2860
+ }
2861
+
2862
+ this->notice_receiver = proc;
2863
+ return old_proc;
2864
+ }
2865
+
2866
+
2867
+ /*
2868
+ * Notice callback proxy function -- delegate the callback to the
2869
+ * currently-registered Ruby notice_processor object.
2870
+ */
2871
+ void
2872
+ notice_processor_proxy(void *arg, const char *message)
2873
+ {
2874
+ VALUE self = (VALUE)arg;
2875
+ t_pg_connection *this = pg_get_connection( self );
2876
+
2877
+ if (this->notice_receiver != Qnil) {
2878
+ VALUE message_str = rb_tainted_str_new2(message);
2879
+ PG_ENCODING_SET_NOCHECK( message_str, ENCODING_GET(self) );
2880
+ rb_funcall(this->notice_receiver, rb_intern("call"), 1, message_str);
2881
+ }
2882
+ return;
2883
+ }
2884
+
2885
+ /*
2886
+ * call-seq:
2887
+ * conn.set_notice_processor {|message| ... } -> Proc
2888
+ *
2889
+ * See #set_notice_receiver for the desription of what this and the
2890
+ * notice_processor methods do.
2891
+ *
2892
+ * This function takes a new block to act as the notice processor and returns
2893
+ * the Proc object previously set, or +nil+ if it was previously the default.
2894
+ * The block should accept a single String object.
2895
+ *
2896
+ * If you pass no arguments, it will reset the handler to the default.
2897
+ */
2898
+ static VALUE
2899
+ pgconn_set_notice_processor(VALUE self)
2900
+ {
2901
+ VALUE proc, old_proc;
2902
+ t_pg_connection *this = pg_get_connection_safe( self );
2903
+
2904
+ /* If default_notice_processor is unset, assume that the current
2905
+ * notice processor is the default, and save it to a global variable.
2906
+ * This should not be a problem because the default processor is
2907
+ * always the same, so won't vary among connections.
2908
+ */
2909
+ if(default_notice_processor == NULL)
2910
+ default_notice_processor = PQsetNoticeProcessor(this->pgconn, NULL, NULL);
2911
+
2912
+ old_proc = this->notice_receiver;
2913
+ if( rb_block_given_p() ) {
2914
+ proc = rb_block_proc();
2915
+ PQsetNoticeProcessor(this->pgconn, gvl_notice_processor_proxy, (void *)self);
2916
+ } else {
2917
+ /* if no block is given, set back to default */
2918
+ proc = Qnil;
2919
+ PQsetNoticeProcessor(this->pgconn, default_notice_processor, NULL);
2920
+ }
2921
+
2922
+ this->notice_receiver = proc;
2923
+ return old_proc;
2924
+ }
2925
+
2926
+
2927
+ /*
2928
+ * call-seq:
2929
+ * conn.get_client_encoding() -> String
2930
+ *
2931
+ * Returns the client encoding as a String.
2932
+ */
2933
+ static VALUE
2934
+ pgconn_get_client_encoding(VALUE self)
2935
+ {
2936
+ char *encoding = (char *)pg_encoding_to_char(PQclientEncoding(pg_get_pgconn(self)));
2937
+ return rb_tainted_str_new2(encoding);
2938
+ }
2939
+
2940
+
2941
+ /*
2942
+ * call-seq:
2943
+ * conn.set_client_encoding( encoding )
2944
+ *
2945
+ * Sets the client encoding to the _encoding_ String.
2946
+ */
2947
+ static VALUE
2948
+ pgconn_set_client_encoding(VALUE self, VALUE str)
2949
+ {
2950
+ PGconn *conn = pg_get_pgconn( self );
2951
+
2952
+ Check_Type(str, T_STRING);
2953
+
2954
+ if ( (gvl_PQsetClientEncoding(conn, StringValueCStr(str))) == -1 ) {
2955
+ rb_raise(rb_ePGerror, "%s", PQerrorMessage(conn));
2956
+ }
2957
+ pgconn_set_internal_encoding_index( self );
2958
+
2959
+ return Qnil;
2960
+ }
2961
+
2962
+ /*
2963
+ * call-seq:
2964
+ * conn.transaction { |conn| ... } -> result of the block
2965
+ *
2966
+ * Executes a +BEGIN+ at the start of the block,
2967
+ * and a +COMMIT+ at the end of the block, or
2968
+ * +ROLLBACK+ if any exception occurs.
2969
+ */
2970
+ static VALUE
2971
+ pgconn_transaction(VALUE self)
2972
+ {
2973
+ PGconn *conn = pg_get_pgconn(self);
2974
+ PGresult *result;
2975
+ VALUE rb_pgresult;
2976
+ VALUE block_result = Qnil;
2977
+ int status;
2978
+
2979
+ if (rb_block_given_p()) {
2980
+ result = gvl_PQexec(conn, "BEGIN");
2981
+ rb_pgresult = pg_new_result(result, self);
2982
+ pg_result_check(rb_pgresult);
2983
+ block_result = rb_protect(rb_yield, self, &status);
2984
+ if(status == 0) {
2985
+ result = gvl_PQexec(conn, "COMMIT");
2986
+ rb_pgresult = pg_new_result(result, self);
2987
+ pg_result_check(rb_pgresult);
2988
+ }
2989
+ else {
2990
+ /* exception occurred, ROLLBACK and re-raise */
2991
+ result = gvl_PQexec(conn, "ROLLBACK");
2992
+ rb_pgresult = pg_new_result(result, self);
2993
+ pg_result_check(rb_pgresult);
2994
+ rb_jump_tag(status);
2995
+ }
2996
+
2997
+ }
2998
+ else {
2999
+ /* no block supplied? */
3000
+ rb_raise(rb_eArgError, "Must supply block for PG::Connection#transaction");
3001
+ }
3002
+ return block_result;
3003
+ }
3004
+
3005
+
3006
+ /*
3007
+ * call-seq:
3008
+ * conn.quote_ident( str ) -> String
3009
+ * conn.quote_ident( array ) -> String
3010
+ * PG::Connection.quote_ident( str ) -> String
3011
+ * PG::Connection.quote_ident( array ) -> String
3012
+ *
3013
+ * Returns a string that is safe for inclusion in a SQL query as an
3014
+ * identifier. Note: this is not a quote function for values, but for
3015
+ * identifiers.
3016
+ *
3017
+ * For example, in a typical SQL query: <tt>SELECT FOO FROM MYTABLE</tt>
3018
+ * The identifier <tt>FOO</tt> is folded to lower case, so it actually
3019
+ * means <tt>foo</tt>. If you really want to access the case-sensitive
3020
+ * field name <tt>FOO</tt>, use this function like
3021
+ * <tt>conn.quote_ident('FOO')</tt>, which will return <tt>"FOO"</tt>
3022
+ * (with double-quotes). PostgreSQL will see the double-quotes, and
3023
+ * it will not fold to lower case.
3024
+ *
3025
+ * Similarly, this function also protects against special characters,
3026
+ * and other things that might allow SQL injection if the identifier
3027
+ * comes from an untrusted source.
3028
+ *
3029
+ * If the parameter is an Array, then all it's values are separately quoted
3030
+ * and then joined by a "." character. This can be used for identifiers in
3031
+ * the form "schema"."table"."column" .
3032
+ *
3033
+ * This method is functional identical to the encoder PG::TextEncoder::Identifier .
3034
+ *
3035
+ * If the instance method form is used and the input string character encoding
3036
+ * is different to the connection encoding, then the string is converted to this
3037
+ * encoding, so that the returned string is always encoded as PG::Connection#internal_encoding .
3038
+ *
3039
+ * In the singleton form (PG::Connection.quote_ident) the character encoding
3040
+ * of the result string is set to the character encoding of the input string.
3041
+ */
3042
+ static VALUE
3043
+ pgconn_s_quote_ident(VALUE self, VALUE str_or_array)
3044
+ {
3045
+ VALUE ret;
3046
+ int enc_idx;
3047
+
3048
+ if( rb_obj_is_kind_of(self, rb_cPGconn) ){
3049
+ enc_idx = ENCODING_GET( self );
3050
+ }else{
3051
+ enc_idx = RB_TYPE_P(str_or_array, T_STRING) ? ENCODING_GET( str_or_array ) : rb_ascii8bit_encindex();
3052
+ }
3053
+ pg_text_enc_identifier(NULL, str_or_array, NULL, &ret, enc_idx);
3054
+
3055
+ OBJ_INFECT(ret, str_or_array);
3056
+
3057
+ return ret;
3058
+ }
3059
+
3060
+
3061
+ static void *
3062
+ get_result_readable(PGconn *conn)
3063
+ {
3064
+ return gvl_PQisBusy(conn) ? NULL : (void*)1;
3065
+ }
3066
+
3067
+
3068
+ /*
3069
+ * call-seq:
3070
+ * conn.block( [ timeout ] ) -> Boolean
3071
+ *
3072
+ * Blocks until the server is no longer busy, or until the
3073
+ * optional _timeout_ is reached, whichever comes first.
3074
+ * _timeout_ is measured in seconds and can be fractional.
3075
+ *
3076
+ * Returns +false+ if _timeout_ is reached, +true+ otherwise.
3077
+ *
3078
+ * If +true+ is returned, +conn.is_busy+ will return +false+
3079
+ * and +conn.get_result+ will not block.
3080
+ */
3081
+ static VALUE
3082
+ pgconn_block( int argc, VALUE *argv, VALUE self ) {
3083
+ PGconn *conn = pg_get_pgconn( self );
3084
+
3085
+ struct timeval timeout;
3086
+ struct timeval *ptimeout = NULL;
3087
+ VALUE timeout_in;
3088
+ double timeout_sec;
3089
+ void *ret;
3090
+
3091
+ if ( rb_scan_args(argc, argv, "01", &timeout_in) == 1 ) {
3092
+ timeout_sec = NUM2DBL( timeout_in );
3093
+ timeout.tv_sec = (time_t)timeout_sec;
3094
+ timeout.tv_usec = (suseconds_t)((timeout_sec - (long)timeout_sec) * 1e6);
3095
+ ptimeout = &timeout;
3096
+ }
3097
+
3098
+ ret = wait_socket_readable( conn, ptimeout, get_result_readable);
3099
+
3100
+ if( !ret )
3101
+ return Qfalse;
3102
+
3103
+ return Qtrue;
3104
+ }
3105
+
3106
+
3107
+ /*
3108
+ * call-seq:
3109
+ * conn.get_last_result( ) -> PG::Result
3110
+ *
3111
+ * This function retrieves all available results
3112
+ * on the current connection (from previously issued
3113
+ * asynchronous commands like +send_query()+) and
3114
+ * returns the last non-NULL result, or +nil+ if no
3115
+ * results are available.
3116
+ *
3117
+ * This function is similar to #get_result
3118
+ * except that it is designed to get one and only
3119
+ * one result.
3120
+ */
3121
+ static VALUE
3122
+ pgconn_get_last_result(VALUE self)
3123
+ {
3124
+ PGconn *conn = pg_get_pgconn(self);
3125
+ VALUE rb_pgresult = Qnil;
3126
+ PGresult *cur, *prev;
3127
+
3128
+
3129
+ cur = prev = NULL;
3130
+ while ((cur = gvl_PQgetResult(conn)) != NULL) {
3131
+ int status;
3132
+
3133
+ if (prev) PQclear(prev);
3134
+ prev = cur;
3135
+
3136
+ status = PQresultStatus(cur);
3137
+ if (status == PGRES_COPY_OUT || status == PGRES_COPY_IN)
3138
+ break;
3139
+ }
3140
+
3141
+ if (prev) {
3142
+ rb_pgresult = pg_new_result( prev, self );
3143
+ pg_result_check(rb_pgresult);
3144
+ }
3145
+
3146
+ return rb_pgresult;
3147
+ }
3148
+
3149
+ /*
3150
+ * call-seq:
3151
+ * conn.discard_results()
3152
+ *
3153
+ * Silently discard any prior query result that application didn't eat.
3154
+ * This is done prior of Connection#exec and sibling methods and can
3155
+ * be called explicitly when using the async API.
3156
+ */
3157
+ static VALUE
3158
+ pgconn_discard_results(VALUE self)
3159
+ {
3160
+ PGconn *conn = pg_get_pgconn(self);
3161
+
3162
+ PGresult *cur;
3163
+ while ((cur = gvl_PQgetResult(conn)) != NULL) {
3164
+ int status = PQresultStatus(cur);
3165
+ PQclear(cur);
3166
+ if (status == PGRES_COPY_IN){
3167
+ gvl_PQputCopyEnd(conn, "COPY terminated by new PQexec");
3168
+ }
3169
+ if (status == PGRES_COPY_OUT){
3170
+ char *buffer = NULL;
3171
+ while( gvl_PQgetCopyData(conn, &buffer, 0) > 0)
3172
+ PQfreemem(buffer);
3173
+ }
3174
+ }
3175
+
3176
+ return Qnil;
3177
+ }
3178
+
3179
+ /*
3180
+ * call-seq:
3181
+ * conn.async_exec(sql) -> PG::Result
3182
+ * conn.async_exec(sql) {|pg_result| block }
3183
+ *
3184
+ * This function has the same behavior as #sync_exec,
3185
+ * but is implemented using the asynchronous command
3186
+ * processing API of libpq.
3187
+ *
3188
+ * Both #sync_exec and #async_exec release the GVL while waiting for server response, so that concurrent threads will get executed.
3189
+ * However #async_exec has two advantages:
3190
+ *
3191
+ * 1. #async_exec can be aborted by signals (like Ctrl-C), while #exec blocks signal processing until the query is answered.
3192
+ * 2. Ruby VM gets notified about IO blocked operations.
3193
+ * It can therefore schedule thing like garbage collection, while queries are running like in this proposal: https://bugs.ruby-lang.org/issues/14723
3194
+ */
3195
+ static VALUE
3196
+ pgconn_async_exec(int argc, VALUE *argv, VALUE self)
3197
+ {
3198
+ VALUE rb_pgresult = Qnil;
3199
+
3200
+ pgconn_discard_results( self );
3201
+ pgconn_send_query( argc, argv, self );
3202
+ pgconn_block( 0, NULL, self ); /* wait for input (without blocking) before reading the last result */
3203
+ rb_pgresult = pgconn_get_last_result( self );
3204
+
3205
+ if ( rb_block_given_p() ) {
3206
+ return rb_ensure( rb_yield, rb_pgresult, pg_result_clear, rb_pgresult );
3207
+ }
3208
+ return rb_pgresult;
3209
+ }
3210
+
3211
+
3212
+ /*
3213
+ * call-seq:
3214
+ * conn.async_exec_params(sql, params [, result_format [, type_map ]] ) -> nil
3215
+ * conn.async_exec_params(sql, params [, result_format [, type_map ]] ) {|pg_result| block }
3216
+ *
3217
+ * This function has the same behavior as #sync_exec_params, but is implemented using the asynchronous command processing API of libpq.
3218
+ * See #async_exec for the differences between the two API variants.
3219
+ */
3220
+ static VALUE
3221
+ pgconn_async_exec_params(int argc, VALUE *argv, VALUE self)
3222
+ {
3223
+ VALUE rb_pgresult = Qnil;
3224
+
3225
+ pgconn_discard_results( self );
3226
+ /* If called with no or nil parameters, use PQsendQuery for compatibility */
3227
+ if ( argc == 1 || (argc >= 2 && argc <= 4 && NIL_P(argv[1]) )) {
3228
+ pg_deprecated(3, ("forwarding async_exec_params to async_exec is deprecated"));
3229
+ pgconn_send_query( argc, argv, self );
3230
+ } else {
3231
+ pgconn_send_query_params( argc, argv, self );
3232
+ }
3233
+ pgconn_block( 0, NULL, self ); /* wait for input (without blocking) before reading the last result */
3234
+ rb_pgresult = pgconn_get_last_result( self );
3235
+
3236
+ if ( rb_block_given_p() ) {
3237
+ return rb_ensure( rb_yield, rb_pgresult, pg_result_clear, rb_pgresult );
3238
+ }
3239
+ return rb_pgresult;
3240
+ }
3241
+
3242
+
3243
+ /*
3244
+ * call-seq:
3245
+ * conn.async_prepare(stmt_name, sql [, param_types ] ) -> PG::Result
3246
+ *
3247
+ * This function has the same behavior as #sync_prepare, but is implemented using the asynchronous command processing API of libpq.
3248
+ * See #async_exec for the differences between the two API variants.
3249
+ */
3250
+ static VALUE
3251
+ pgconn_async_prepare(int argc, VALUE *argv, VALUE self)
3252
+ {
3253
+ VALUE rb_pgresult = Qnil;
3254
+
3255
+ pgconn_discard_results( self );
3256
+ pgconn_send_prepare( argc, argv, self );
3257
+ pgconn_block( 0, NULL, self ); /* wait for input (without blocking) before reading the last result */
3258
+ rb_pgresult = pgconn_get_last_result( self );
3259
+
3260
+ if ( rb_block_given_p() ) {
3261
+ return rb_ensure( rb_yield, rb_pgresult, pg_result_clear, rb_pgresult );
3262
+ }
3263
+ return rb_pgresult;
3264
+ }
3265
+
3266
+
3267
+ /*
3268
+ * call-seq:
3269
+ * conn.async_exec_prepared(statement_name [, params, result_format[, type_map]] ) -> PG::Result
3270
+ * conn.async_exec_prepared(statement_name [, params, result_format[, type_map]] ) {|pg_result| block }
3271
+ *
3272
+ * This function has the same behavior as #sync_exec_prepared, but is implemented using the asynchronous command processing API of libpq.
3273
+ * See #async_exec for the differences between the two API variants.
3274
+ */
3275
+ static VALUE
3276
+ pgconn_async_exec_prepared(int argc, VALUE *argv, VALUE self)
3277
+ {
3278
+ VALUE rb_pgresult = Qnil;
3279
+
3280
+ pgconn_discard_results( self );
3281
+ pgconn_send_query_prepared( argc, argv, self );
3282
+ pgconn_block( 0, NULL, self ); /* wait for input (without blocking) before reading the last result */
3283
+ rb_pgresult = pgconn_get_last_result( self );
3284
+
3285
+ if ( rb_block_given_p() ) {
3286
+ return rb_ensure( rb_yield, rb_pgresult, pg_result_clear, rb_pgresult );
3287
+ }
3288
+ return rb_pgresult;
3289
+ }
3290
+
3291
+
3292
+ /*
3293
+ * call-seq:
3294
+ * conn.async_describe_portal( portal_name ) -> PG::Result
3295
+ *
3296
+ * This function has the same behavior as #sync_describe_portal, but is implemented using the asynchronous command processing API of libpq.
3297
+ * See #async_exec for the differences between the two API variants.
3298
+ */
3299
+ static VALUE
3300
+ pgconn_async_describe_portal(VALUE self, VALUE portal)
3301
+ {
3302
+ VALUE rb_pgresult = Qnil;
3303
+
3304
+ pgconn_discard_results( self );
3305
+ pgconn_send_describe_portal( self, portal );
3306
+ pgconn_block( 0, NULL, self ); /* wait for input (without blocking) before reading the last result */
3307
+ rb_pgresult = pgconn_get_last_result( self );
3308
+
3309
+ if ( rb_block_given_p() ) {
3310
+ return rb_ensure( rb_yield, rb_pgresult, pg_result_clear, rb_pgresult );
3311
+ }
3312
+ return rb_pgresult;
3313
+ }
3314
+
3315
+
3316
+ /*
3317
+ * call-seq:
3318
+ * conn.async_describe_prepared( statement_name ) -> PG::Result
3319
+ *
3320
+ * This function has the same behavior as #sync_describe_prepared, but is implemented using the asynchronous command processing API of libpq.
3321
+ * See #async_exec for the differences between the two API variants.
3322
+ */
3323
+ static VALUE
3324
+ pgconn_async_describe_prepared(VALUE self, VALUE stmt_name)
3325
+ {
3326
+ VALUE rb_pgresult = Qnil;
3327
+
3328
+ pgconn_discard_results( self );
3329
+ pgconn_send_describe_prepared( self, stmt_name );
3330
+ pgconn_block( 0, NULL, self ); /* wait for input (without blocking) before reading the last result */
3331
+ rb_pgresult = pgconn_get_last_result( self );
3332
+
3333
+ if ( rb_block_given_p() ) {
3334
+ return rb_ensure( rb_yield, rb_pgresult, pg_result_clear, rb_pgresult );
3335
+ }
3336
+ return rb_pgresult;
3337
+ }
3338
+
3339
+
3340
+ #ifdef HAVE_PQSSLATTRIBUTE
3341
+ /*
3342
+ * call-seq:
3343
+ * conn.ssl_in_use? -> Boolean
3344
+ *
3345
+ * Returns +true+ if the connection uses SSL, +false+ if not.
3346
+ *
3347
+ * Available since PostgreSQL-9.5
3348
+ */
3349
+ static VALUE
3350
+ pgconn_ssl_in_use(VALUE self)
3351
+ {
3352
+ return PQsslInUse(pg_get_pgconn(self)) ? Qtrue : Qfalse;
3353
+ }
3354
+
3355
+
3356
+ /*
3357
+ * call-seq:
3358
+ * conn.ssl_attribute(attribute_name) -> String
3359
+ *
3360
+ * Returns SSL-related information about the connection.
3361
+ *
3362
+ * The list of available attributes varies depending on the SSL library being used,
3363
+ * and the type of connection. If an attribute is not available, returns nil.
3364
+ *
3365
+ * The following attributes are commonly available:
3366
+ *
3367
+ * [+library+]
3368
+ * Name of the SSL implementation in use. (Currently, only "OpenSSL" is implemented)
3369
+ * [+protocol+]
3370
+ * SSL/TLS version in use. Common values are "SSLv2", "SSLv3", "TLSv1", "TLSv1.1" and "TLSv1.2", but an implementation may return other strings if some other protocol is used.
3371
+ * [+key_bits+]
3372
+ * Number of key bits used by the encryption algorithm.
3373
+ * [+cipher+]
3374
+ * A short name of the ciphersuite used, e.g. "DHE-RSA-DES-CBC3-SHA". The names are specific to each SSL implementation.
3375
+ * [+compression+]
3376
+ * If SSL compression is in use, returns the name of the compression algorithm, or "on" if compression is used but the algorithm is not known. If compression is not in use, returns "off".
3377
+ *
3378
+ *
3379
+ * See also #ssl_attribute_names and http://www.postgresql.org/docs/current/interactive/libpq-status.html#LIBPQ-PQSSLATTRIBUTE
3380
+ *
3381
+ * Available since PostgreSQL-9.5
3382
+ */
3383
+ static VALUE
3384
+ pgconn_ssl_attribute(VALUE self, VALUE attribute_name)
3385
+ {
3386
+ const char *p_attr;
3387
+
3388
+ p_attr = PQsslAttribute(pg_get_pgconn(self), StringValueCStr(attribute_name));
3389
+ return p_attr ? rb_str_new_cstr(p_attr) : Qnil;
3390
+ }
3391
+
3392
+ /*
3393
+ * call-seq:
3394
+ * conn.ssl_attribute_names -> Array<String>
3395
+ *
3396
+ * Return an array of SSL attribute names available.
3397
+ *
3398
+ * See also #ssl_attribute
3399
+ *
3400
+ * Available since PostgreSQL-9.5
3401
+ */
3402
+ static VALUE
3403
+ pgconn_ssl_attribute_names(VALUE self)
3404
+ {
3405
+ int i;
3406
+ const char * const * p_list = PQsslAttributeNames(pg_get_pgconn(self));
3407
+ VALUE ary = rb_ary_new();
3408
+
3409
+ for ( i = 0; p_list[i]; i++ ) {
3410
+ rb_ary_push( ary, rb_str_new_cstr( p_list[i] ));
3411
+ }
3412
+ return ary;
3413
+ }
3414
+
3415
+
3416
+ #endif
3417
+
3418
+
3419
+ /**************************************************************************
3420
+ * LARGE OBJECT SUPPORT
3421
+ **************************************************************************/
3422
+
3423
+ /*
3424
+ * call-seq:
3425
+ * conn.lo_creat( [mode] ) -> Integer
3426
+ *
3427
+ * Creates a large object with mode _mode_. Returns a large object Oid.
3428
+ * On failure, it raises PG::Error.
3429
+ */
3430
+ static VALUE
3431
+ pgconn_locreat(int argc, VALUE *argv, VALUE self)
3432
+ {
3433
+ Oid lo_oid;
3434
+ int mode;
3435
+ VALUE nmode;
3436
+ PGconn *conn = pg_get_pgconn(self);
3437
+
3438
+ if (rb_scan_args(argc, argv, "01", &nmode) == 0)
3439
+ mode = INV_READ;
3440
+ else
3441
+ mode = NUM2INT(nmode);
3442
+
3443
+ lo_oid = lo_creat(conn, mode);
3444
+ if (lo_oid == 0)
3445
+ rb_raise(rb_ePGerror, "lo_creat failed");
3446
+
3447
+ return UINT2NUM(lo_oid);
3448
+ }
3449
+
3450
+ /*
3451
+ * call-seq:
3452
+ * conn.lo_create( oid ) -> Integer
3453
+ *
3454
+ * Creates a large object with oid _oid_. Returns the large object Oid.
3455
+ * On failure, it raises PG::Error.
3456
+ */
3457
+ static VALUE
3458
+ pgconn_locreate(VALUE self, VALUE in_lo_oid)
3459
+ {
3460
+ Oid ret, lo_oid;
3461
+ PGconn *conn = pg_get_pgconn(self);
3462
+ lo_oid = NUM2UINT(in_lo_oid);
3463
+
3464
+ ret = lo_create(conn, lo_oid);
3465
+ if (ret == InvalidOid)
3466
+ rb_raise(rb_ePGerror, "lo_create failed");
3467
+
3468
+ return UINT2NUM(ret);
3469
+ }
3470
+
3471
+ /*
3472
+ * call-seq:
3473
+ * conn.lo_import(file) -> Integer
3474
+ *
3475
+ * Import a file to a large object. Returns a large object Oid.
3476
+ *
3477
+ * On failure, it raises a PG::Error.
3478
+ */
3479
+ static VALUE
3480
+ pgconn_loimport(VALUE self, VALUE filename)
3481
+ {
3482
+ Oid lo_oid;
3483
+
3484
+ PGconn *conn = pg_get_pgconn(self);
3485
+
3486
+ Check_Type(filename, T_STRING);
3487
+
3488
+ lo_oid = lo_import(conn, StringValueCStr(filename));
3489
+ if (lo_oid == 0) {
3490
+ rb_raise(rb_ePGerror, "%s", PQerrorMessage(conn));
3491
+ }
3492
+ return UINT2NUM(lo_oid);
3493
+ }
3494
+
3495
+ /*
3496
+ * call-seq:
3497
+ * conn.lo_export( oid, file ) -> nil
3498
+ *
3499
+ * Saves a large object of _oid_ to a _file_.
3500
+ */
3501
+ static VALUE
3502
+ pgconn_loexport(VALUE self, VALUE lo_oid, VALUE filename)
3503
+ {
3504
+ PGconn *conn = pg_get_pgconn(self);
3505
+ Oid oid;
3506
+ Check_Type(filename, T_STRING);
3507
+
3508
+ oid = NUM2UINT(lo_oid);
3509
+
3510
+ if (lo_export(conn, oid, StringValueCStr(filename)) < 0) {
3511
+ rb_raise(rb_ePGerror, "%s", PQerrorMessage(conn));
3512
+ }
3513
+ return Qnil;
3514
+ }
3515
+
3516
+ /*
3517
+ * call-seq:
3518
+ * conn.lo_open( oid, [mode] ) -> Integer
3519
+ *
3520
+ * Open a large object of _oid_. Returns a large object descriptor
3521
+ * instance on success. The _mode_ argument specifies the mode for
3522
+ * the opened large object,which is either +INV_READ+, or +INV_WRITE+.
3523
+ *
3524
+ * If _mode_ is omitted, the default is +INV_READ+.
3525
+ */
3526
+ static VALUE
3527
+ pgconn_loopen(int argc, VALUE *argv, VALUE self)
3528
+ {
3529
+ Oid lo_oid;
3530
+ int fd, mode;
3531
+ VALUE nmode, selfid;
3532
+ PGconn *conn = pg_get_pgconn(self);
3533
+
3534
+ rb_scan_args(argc, argv, "11", &selfid, &nmode);
3535
+ lo_oid = NUM2UINT(selfid);
3536
+ if(NIL_P(nmode))
3537
+ mode = INV_READ;
3538
+ else
3539
+ mode = NUM2INT(nmode);
3540
+
3541
+ if((fd = lo_open(conn, lo_oid, mode)) < 0) {
3542
+ rb_raise(rb_ePGerror, "can't open large object: %s", PQerrorMessage(conn));
3543
+ }
3544
+ return INT2FIX(fd);
3545
+ }
3546
+
3547
+ /*
3548
+ * call-seq:
3549
+ * conn.lo_write( lo_desc, buffer ) -> Integer
3550
+ *
3551
+ * Writes the string _buffer_ to the large object _lo_desc_.
3552
+ * Returns the number of bytes written.
3553
+ */
3554
+ static VALUE
3555
+ pgconn_lowrite(VALUE self, VALUE in_lo_desc, VALUE buffer)
3556
+ {
3557
+ int n;
3558
+ PGconn *conn = pg_get_pgconn(self);
3559
+ int fd = NUM2INT(in_lo_desc);
3560
+
3561
+ Check_Type(buffer, T_STRING);
3562
+
3563
+ if( RSTRING_LEN(buffer) < 0) {
3564
+ rb_raise(rb_ePGerror, "write buffer zero string");
3565
+ }
3566
+ if((n = lo_write(conn, fd, StringValuePtr(buffer),
3567
+ RSTRING_LEN(buffer))) < 0) {
3568
+ rb_raise(rb_ePGerror, "lo_write failed: %s", PQerrorMessage(conn));
3569
+ }
3570
+
3571
+ return INT2FIX(n);
3572
+ }
3573
+
3574
+ /*
3575
+ * call-seq:
3576
+ * conn.lo_read( lo_desc, len ) -> String
3577
+ *
3578
+ * Attempts to read _len_ bytes from large object _lo_desc_,
3579
+ * returns resulting data.
3580
+ */
3581
+ static VALUE
3582
+ pgconn_loread(VALUE self, VALUE in_lo_desc, VALUE in_len)
3583
+ {
3584
+ int ret;
3585
+ PGconn *conn = pg_get_pgconn(self);
3586
+ int len = NUM2INT(in_len);
3587
+ int lo_desc = NUM2INT(in_lo_desc);
3588
+ VALUE str;
3589
+ char *buffer;
3590
+
3591
+ buffer = ALLOC_N(char, len);
3592
+ if(buffer == NULL)
3593
+ rb_raise(rb_eNoMemError, "ALLOC failed!");
3594
+
3595
+ if (len < 0){
3596
+ rb_raise(rb_ePGerror,"nagative length %d given", len);
3597
+ }
3598
+
3599
+ if((ret = lo_read(conn, lo_desc, buffer, len)) < 0)
3600
+ rb_raise(rb_ePGerror, "lo_read failed");
3601
+
3602
+ if(ret == 0) {
3603
+ xfree(buffer);
3604
+ return Qnil;
3605
+ }
3606
+
3607
+ str = rb_tainted_str_new(buffer, ret);
3608
+ xfree(buffer);
3609
+
3610
+ return str;
3611
+ }
3612
+
3613
+
3614
+ /*
3615
+ * call-seq:
3616
+ * conn.lo_lseek( lo_desc, offset, whence ) -> Integer
3617
+ *
3618
+ * Move the large object pointer _lo_desc_ to offset _offset_.
3619
+ * Valid values for _whence_ are +SEEK_SET+, +SEEK_CUR+, and +SEEK_END+.
3620
+ * (Or 0, 1, or 2.)
3621
+ */
3622
+ static VALUE
3623
+ pgconn_lolseek(VALUE self, VALUE in_lo_desc, VALUE offset, VALUE whence)
3624
+ {
3625
+ PGconn *conn = pg_get_pgconn(self);
3626
+ int lo_desc = NUM2INT(in_lo_desc);
3627
+ int ret;
3628
+
3629
+ if((ret = lo_lseek(conn, lo_desc, NUM2INT(offset), NUM2INT(whence))) < 0) {
3630
+ rb_raise(rb_ePGerror, "lo_lseek failed");
3631
+ }
3632
+
3633
+ return INT2FIX(ret);
3634
+ }
3635
+
3636
+ /*
3637
+ * call-seq:
3638
+ * conn.lo_tell( lo_desc ) -> Integer
3639
+ *
3640
+ * Returns the current position of the large object _lo_desc_.
3641
+ */
3642
+ static VALUE
3643
+ pgconn_lotell(VALUE self, VALUE in_lo_desc)
3644
+ {
3645
+ int position;
3646
+ PGconn *conn = pg_get_pgconn(self);
3647
+ int lo_desc = NUM2INT(in_lo_desc);
3648
+
3649
+ if((position = lo_tell(conn, lo_desc)) < 0)
3650
+ rb_raise(rb_ePGerror,"lo_tell failed");
3651
+
3652
+ return INT2FIX(position);
3653
+ }
3654
+
3655
+ /*
3656
+ * call-seq:
3657
+ * conn.lo_truncate( lo_desc, len ) -> nil
3658
+ *
3659
+ * Truncates the large object _lo_desc_ to size _len_.
3660
+ */
3661
+ static VALUE
3662
+ pgconn_lotruncate(VALUE self, VALUE in_lo_desc, VALUE in_len)
3663
+ {
3664
+ PGconn *conn = pg_get_pgconn(self);
3665
+ int lo_desc = NUM2INT(in_lo_desc);
3666
+ size_t len = NUM2INT(in_len);
3667
+
3668
+ if(lo_truncate(conn,lo_desc,len) < 0)
3669
+ rb_raise(rb_ePGerror,"lo_truncate failed");
3670
+
3671
+ return Qnil;
3672
+ }
3673
+
3674
+ /*
3675
+ * call-seq:
3676
+ * conn.lo_close( lo_desc ) -> nil
3677
+ *
3678
+ * Closes the postgres large object of _lo_desc_.
3679
+ */
3680
+ static VALUE
3681
+ pgconn_loclose(VALUE self, VALUE in_lo_desc)
3682
+ {
3683
+ PGconn *conn = pg_get_pgconn(self);
3684
+ int lo_desc = NUM2INT(in_lo_desc);
3685
+
3686
+ if(lo_close(conn,lo_desc) < 0)
3687
+ rb_raise(rb_ePGerror,"lo_close failed");
3688
+
3689
+ return Qnil;
3690
+ }
3691
+
3692
+ /*
3693
+ * call-seq:
3694
+ * conn.lo_unlink( oid ) -> nil
3695
+ *
3696
+ * Unlinks (deletes) the postgres large object of _oid_.
3697
+ */
3698
+ static VALUE
3699
+ pgconn_lounlink(VALUE self, VALUE in_oid)
3700
+ {
3701
+ PGconn *conn = pg_get_pgconn(self);
3702
+ Oid oid = NUM2UINT(in_oid);
3703
+
3704
+ if(lo_unlink(conn,oid) < 0)
3705
+ rb_raise(rb_ePGerror,"lo_unlink failed");
3706
+
3707
+ return Qnil;
3708
+ }
3709
+
3710
+
3711
+ void
3712
+ pgconn_set_internal_encoding_index( VALUE self )
3713
+ {
3714
+ PGconn *conn = pg_get_pgconn(self);
3715
+ rb_encoding *enc = pg_conn_enc_get( conn );
3716
+ PG_ENCODING_SET_NOCHECK( self, rb_enc_to_index(enc));
3717
+ }
3718
+
3719
+ /*
3720
+ * call-seq:
3721
+ * conn.internal_encoding -> Encoding
3722
+ *
3723
+ * defined in Ruby 1.9 or later.
3724
+ *
3725
+ * Returns:
3726
+ * * an Encoding - client_encoding of the connection as a Ruby Encoding object.
3727
+ * * nil - the client_encoding is 'SQL_ASCII'
3728
+ */
3729
+ static VALUE
3730
+ pgconn_internal_encoding(VALUE self)
3731
+ {
3732
+ PGconn *conn = pg_get_pgconn( self );
3733
+ rb_encoding *enc = pg_conn_enc_get( conn );
3734
+
3735
+ if ( enc ) {
3736
+ return rb_enc_from_encoding( enc );
3737
+ } else {
3738
+ return Qnil;
3739
+ }
3740
+ }
3741
+
3742
+ static VALUE pgconn_external_encoding(VALUE self);
3743
+
3744
+ /*
3745
+ * call-seq:
3746
+ * conn.internal_encoding = value
3747
+ *
3748
+ * A wrapper of #set_client_encoding.
3749
+ * defined in Ruby 1.9 or later.
3750
+ *
3751
+ * +value+ can be one of:
3752
+ * * an Encoding
3753
+ * * a String - a name of Encoding
3754
+ * * +nil+ - sets the client_encoding to SQL_ASCII.
3755
+ */
3756
+ static VALUE
3757
+ pgconn_internal_encoding_set(VALUE self, VALUE enc)
3758
+ {
3759
+ VALUE enc_inspect;
3760
+ if (NIL_P(enc)) {
3761
+ pgconn_set_client_encoding( self, rb_usascii_str_new_cstr("SQL_ASCII") );
3762
+ return enc;
3763
+ }
3764
+ else if ( TYPE(enc) == T_STRING && strcasecmp("JOHAB", StringValueCStr(enc)) == 0 ) {
3765
+ pgconn_set_client_encoding(self, rb_usascii_str_new_cstr("JOHAB"));
3766
+ return enc;
3767
+ }
3768
+ else {
3769
+ rb_encoding *rbenc = rb_to_encoding( enc );
3770
+ const char *name = pg_get_rb_encoding_as_pg_encoding( rbenc );
3771
+
3772
+ if ( gvl_PQsetClientEncoding(pg_get_pgconn( self ), name) == -1 ) {
3773
+ VALUE server_encoding = pgconn_external_encoding( self );
3774
+ rb_raise( rb_eEncCompatError, "incompatible character encodings: %s and %s",
3775
+ rb_enc_name(rb_to_encoding(server_encoding)), name );
3776
+ }
3777
+ pgconn_set_internal_encoding_index( self );
3778
+ return enc;
3779
+ }
3780
+
3781
+ enc_inspect = rb_inspect(enc);
3782
+ rb_raise( rb_ePGerror, "unknown encoding: %s", StringValueCStr(enc_inspect) );
3783
+
3784
+ return Qnil;
3785
+ }
3786
+
3787
+
3788
+
3789
+ /*
3790
+ * call-seq:
3791
+ * conn.external_encoding() -> Encoding
3792
+ *
3793
+ * Return the +server_encoding+ of the connected database as a Ruby Encoding object.
3794
+ * The <tt>SQL_ASCII</tt> encoding is mapped to to <tt>ASCII_8BIT</tt>.
3795
+ */
3796
+ static VALUE
3797
+ pgconn_external_encoding(VALUE self)
3798
+ {
3799
+ t_pg_connection *this = pg_get_connection_safe( self );
3800
+ rb_encoding *enc = NULL;
3801
+ const char *pg_encname = NULL;
3802
+
3803
+ /* Use cached value if found */
3804
+ if ( RTEST(this->external_encoding) ) return this->external_encoding;
3805
+
3806
+ pg_encname = PQparameterStatus( this->pgconn, "server_encoding" );
3807
+ enc = pg_get_pg_encname_as_rb_encoding( pg_encname );
3808
+ this->external_encoding = rb_enc_from_encoding( enc );
3809
+
3810
+ return this->external_encoding;
3811
+ }
3812
+
3813
+
3814
+ static VALUE
3815
+ pgconn_set_client_encoding_async1( VALUE args )
3816
+ {
3817
+ VALUE self = ((VALUE*)args)[0];
3818
+ VALUE encname = ((VALUE*)args)[1];
3819
+ VALUE query_format = rb_str_new_cstr("set client_encoding to '%s'");
3820
+ VALUE query = rb_funcall(query_format, rb_intern("%"), 1, encname);
3821
+
3822
+ pgconn_async_exec(1, &query, self);
3823
+ return 0;
3824
+ }
3825
+
3826
+
3827
+ static VALUE
3828
+ pgconn_set_client_encoding_async2( VALUE arg )
3829
+ {
3830
+ UNUSED(arg);
3831
+ return 1;
3832
+ }
3833
+
3834
+
3835
+ static VALUE
3836
+ pgconn_set_client_encoding_async( VALUE self, const char *encname )
3837
+ {
3838
+ VALUE args[] = { self, rb_str_new_cstr(encname) };
3839
+ return rb_rescue(pgconn_set_client_encoding_async1, (VALUE)&args, pgconn_set_client_encoding_async2, Qnil);
3840
+ }
3841
+
3842
+
3843
+ /*
3844
+ * call-seq:
3845
+ * conn.set_default_encoding() -> Encoding
3846
+ *
3847
+ * If Ruby has its Encoding.default_internal set, set PostgreSQL's client_encoding
3848
+ * to match. Returns the new Encoding, or +nil+ if the default internal encoding
3849
+ * wasn't set.
3850
+ */
3851
+ static VALUE
3852
+ pgconn_set_default_encoding( VALUE self )
3853
+ {
3854
+ PGconn *conn = pg_get_pgconn( self );
3855
+ rb_encoding *enc;
3856
+ const char *encname;
3857
+
3858
+ if (( enc = rb_default_internal_encoding() )) {
3859
+ encname = pg_get_rb_encoding_as_pg_encoding( enc );
3860
+ if ( pgconn_set_client_encoding_async(self, encname) != 0 )
3861
+ rb_warning( "Failed to set the default_internal encoding to %s: '%s'",
3862
+ encname, PQerrorMessage(conn) );
3863
+ pgconn_set_internal_encoding_index( self );
3864
+ return rb_enc_from_encoding( enc );
3865
+ } else {
3866
+ pgconn_set_internal_encoding_index( self );
3867
+ return Qnil;
3868
+ }
3869
+ }
3870
+
3871
+
3872
+ /*
3873
+ * call-seq:
3874
+ * res.type_map_for_queries = typemap
3875
+ *
3876
+ * Set the default TypeMap that is used for type casts of query bind parameters.
3877
+ *
3878
+ * +typemap+ must be a kind of PG::TypeMap .
3879
+ *
3880
+ */
3881
+ static VALUE
3882
+ pgconn_type_map_for_queries_set(VALUE self, VALUE typemap)
3883
+ {
3884
+ t_pg_connection *this = pg_get_connection( self );
3885
+
3886
+ if ( !rb_obj_is_kind_of(typemap, rb_cTypeMap) ) {
3887
+ rb_raise( rb_eTypeError, "wrong argument type %s (expected kind of PG::TypeMap)",
3888
+ rb_obj_classname( typemap ) );
3889
+ }
3890
+ Check_Type(typemap, T_DATA);
3891
+ this->type_map_for_queries = typemap;
3892
+
3893
+ return typemap;
3894
+ }
3895
+
3896
+ /*
3897
+ * call-seq:
3898
+ * res.type_map_for_queries -> TypeMap
3899
+ *
3900
+ * Returns the default TypeMap that is currently set for type casts of query
3901
+ * bind parameters.
3902
+ *
3903
+ */
3904
+ static VALUE
3905
+ pgconn_type_map_for_queries_get(VALUE self)
3906
+ {
3907
+ t_pg_connection *this = pg_get_connection( self );
3908
+
3909
+ return this->type_map_for_queries;
3910
+ }
3911
+
3912
+ /*
3913
+ * call-seq:
3914
+ * res.type_map_for_results = typemap
3915
+ *
3916
+ * Set the default TypeMap that is used for type casts of result values.
3917
+ *
3918
+ * +typemap+ must be a kind of PG::TypeMap .
3919
+ *
3920
+ */
3921
+ static VALUE
3922
+ pgconn_type_map_for_results_set(VALUE self, VALUE typemap)
3923
+ {
3924
+ t_pg_connection *this = pg_get_connection( self );
3925
+
3926
+ if ( !rb_obj_is_kind_of(typemap, rb_cTypeMap) ) {
3927
+ rb_raise( rb_eTypeError, "wrong argument type %s (expected kind of PG::TypeMap)",
3928
+ rb_obj_classname( typemap ) );
3929
+ }
3930
+ Check_Type(typemap, T_DATA);
3931
+ this->type_map_for_results = typemap;
3932
+
3933
+ return typemap;
3934
+ }
3935
+
3936
+ /*
3937
+ * call-seq:
3938
+ * res.type_map_for_results -> TypeMap
3939
+ *
3940
+ * Returns the default TypeMap that is currently set for type casts of result values.
3941
+ *
3942
+ */
3943
+ static VALUE
3944
+ pgconn_type_map_for_results_get(VALUE self)
3945
+ {
3946
+ t_pg_connection *this = pg_get_connection( self );
3947
+
3948
+ return this->type_map_for_results;
3949
+ }
3950
+
3951
+
3952
+ /*
3953
+ * call-seq:
3954
+ * res.encoder_for_put_copy_data = encoder
3955
+ *
3956
+ * Set the default coder that is used for type casting of parameters
3957
+ * to #put_copy_data .
3958
+ *
3959
+ * +encoder+ can be:
3960
+ * * a kind of PG::Coder
3961
+ * * +nil+ - disable type encoding, data must be a String.
3962
+ *
3963
+ */
3964
+ static VALUE
3965
+ pgconn_encoder_for_put_copy_data_set(VALUE self, VALUE typemap)
3966
+ {
3967
+ t_pg_connection *this = pg_get_connection( self );
3968
+
3969
+ if( typemap != Qnil ){
3970
+ if ( !rb_obj_is_kind_of(typemap, rb_cPG_Coder) ) {
3971
+ rb_raise( rb_eTypeError, "wrong argument type %s (expected kind of PG::Coder)",
3972
+ rb_obj_classname( typemap ) );
3973
+ }
3974
+ Check_Type(typemap, T_DATA);
3975
+ }
3976
+ this->encoder_for_put_copy_data = typemap;
3977
+
3978
+ return typemap;
3979
+ }
3980
+
3981
+ /*
3982
+ * call-seq:
3983
+ * res.encoder_for_put_copy_data -> PG::Coder
3984
+ *
3985
+ * Returns the default coder object that is currently set for type casting of parameters
3986
+ * to #put_copy_data .
3987
+ *
3988
+ * Returns either:
3989
+ * * a kind of PG::Coder
3990
+ * * +nil+ - type encoding is disabled, data must be a String.
3991
+ *
3992
+ */
3993
+ static VALUE
3994
+ pgconn_encoder_for_put_copy_data_get(VALUE self)
3995
+ {
3996
+ t_pg_connection *this = pg_get_connection( self );
3997
+
3998
+ return this->encoder_for_put_copy_data;
3999
+ }
4000
+
4001
+ /*
4002
+ * call-seq:
4003
+ * res.decoder_for_get_copy_data = decoder
4004
+ *
4005
+ * Set the default coder that is used for type casting of received data
4006
+ * by #get_copy_data .
4007
+ *
4008
+ * +decoder+ can be:
4009
+ * * a kind of PG::Coder
4010
+ * * +nil+ - disable type decoding, returned data will be a String.
4011
+ *
4012
+ */
4013
+ static VALUE
4014
+ pgconn_decoder_for_get_copy_data_set(VALUE self, VALUE typemap)
4015
+ {
4016
+ t_pg_connection *this = pg_get_connection( self );
4017
+
4018
+ if( typemap != Qnil ){
4019
+ if ( !rb_obj_is_kind_of(typemap, rb_cPG_Coder) ) {
4020
+ rb_raise( rb_eTypeError, "wrong argument type %s (expected kind of PG::Coder)",
4021
+ rb_obj_classname( typemap ) );
4022
+ }
4023
+ Check_Type(typemap, T_DATA);
4024
+ }
4025
+ this->decoder_for_get_copy_data = typemap;
4026
+
4027
+ return typemap;
4028
+ }
4029
+
4030
+ /*
4031
+ * call-seq:
4032
+ * res.decoder_for_get_copy_data -> PG::Coder
4033
+ *
4034
+ * Returns the default coder object that is currently set for type casting of received
4035
+ * data by #get_copy_data .
4036
+ *
4037
+ * Returns either:
4038
+ * * a kind of PG::Coder
4039
+ * * +nil+ - type encoding is disabled, returned data will be a String.
4040
+ *
4041
+ */
4042
+ static VALUE
4043
+ pgconn_decoder_for_get_copy_data_get(VALUE self)
4044
+ {
4045
+ t_pg_connection *this = pg_get_connection( self );
4046
+
4047
+ return this->decoder_for_get_copy_data;
4048
+ }
4049
+
4050
+ /*
4051
+ * call-seq:
4052
+ * res.guess_result_memsize = enabled
4053
+ *
4054
+ * This method is for testing only and will probably be removed in the future.
4055
+ */
4056
+ static VALUE
4057
+ pgconn_guess_result_memsize_set(VALUE self, VALUE enable)
4058
+ {
4059
+ t_pg_connection *this = pg_get_connection( self );
4060
+ this->guess_result_memsize = RTEST(enable);
4061
+ return enable;
4062
+ }
4063
+
4064
+
4065
+ /*
4066
+ * Document-class: PG::Connection
4067
+ */
4068
+ void
4069
+ init_pg_connection()
4070
+ {
4071
+ s_id_encode = rb_intern("encode");
4072
+ sym_type = ID2SYM(rb_intern("type"));
4073
+ sym_format = ID2SYM(rb_intern("format"));
4074
+ sym_value = ID2SYM(rb_intern("value"));
4075
+
4076
+ rb_cPGconn = rb_define_class_under( rb_mPG, "Connection", rb_cObject );
4077
+ rb_include_module(rb_cPGconn, rb_mPGconstants);
4078
+
4079
+ /****** PG::Connection CLASS METHODS ******/
4080
+ rb_define_alloc_func( rb_cPGconn, pgconn_s_allocate );
4081
+
4082
+ SINGLETON_ALIAS(rb_cPGconn, "connect", "new");
4083
+ SINGLETON_ALIAS(rb_cPGconn, "open", "new");
4084
+ SINGLETON_ALIAS(rb_cPGconn, "setdb", "new");
4085
+ SINGLETON_ALIAS(rb_cPGconn, "setdblogin", "new");
4086
+ rb_define_singleton_method(rb_cPGconn, "escape_string", pgconn_s_escape, 1);
4087
+ SINGLETON_ALIAS(rb_cPGconn, "escape", "escape_string");
4088
+ rb_define_singleton_method(rb_cPGconn, "escape_bytea", pgconn_s_escape_bytea, 1);
4089
+ rb_define_singleton_method(rb_cPGconn, "unescape_bytea", pgconn_s_unescape_bytea, 1);
4090
+ rb_define_singleton_method(rb_cPGconn, "encrypt_password", pgconn_s_encrypt_password, 2);
4091
+ rb_define_singleton_method(rb_cPGconn, "quote_ident", pgconn_s_quote_ident, 1);
4092
+ rb_define_singleton_method(rb_cPGconn, "connect_start", pgconn_s_connect_start, -1);
4093
+ rb_define_singleton_method(rb_cPGconn, "conndefaults", pgconn_s_conndefaults, 0);
4094
+ rb_define_singleton_method(rb_cPGconn, "ping", pgconn_s_ping, -1);
4095
+
4096
+ /****** PG::Connection INSTANCE METHODS: Connection Control ******/
4097
+ rb_define_method(rb_cPGconn, "initialize", pgconn_init, -1);
4098
+ rb_define_method(rb_cPGconn, "connect_poll", pgconn_connect_poll, 0);
4099
+ rb_define_method(rb_cPGconn, "finish", pgconn_finish, 0);
4100
+ rb_define_method(rb_cPGconn, "finished?", pgconn_finished_p, 0);
4101
+ rb_define_method(rb_cPGconn, "reset", pgconn_reset, 0);
4102
+ rb_define_method(rb_cPGconn, "reset_start", pgconn_reset_start, 0);
4103
+ rb_define_method(rb_cPGconn, "reset_poll", pgconn_reset_poll, 0);
4104
+ rb_define_alias(rb_cPGconn, "close", "finish");
4105
+
4106
+ /****** PG::Connection INSTANCE METHODS: Connection Status ******/
4107
+ rb_define_method(rb_cPGconn, "db", pgconn_db, 0);
4108
+ rb_define_method(rb_cPGconn, "user", pgconn_user, 0);
4109
+ rb_define_method(rb_cPGconn, "pass", pgconn_pass, 0);
4110
+ rb_define_method(rb_cPGconn, "host", pgconn_host, 0);
4111
+ rb_define_method(rb_cPGconn, "port", pgconn_port, 0);
4112
+ rb_define_method(rb_cPGconn, "tty", pgconn_tty, 0);
4113
+ #ifdef HAVE_PQCONNINFO
4114
+ rb_define_method(rb_cPGconn, "conninfo", pgconn_conninfo, 0);
4115
+ #endif
4116
+ rb_define_method(rb_cPGconn, "options", pgconn_options, 0);
4117
+ rb_define_method(rb_cPGconn, "status", pgconn_status, 0);
4118
+ rb_define_method(rb_cPGconn, "transaction_status", pgconn_transaction_status, 0);
4119
+ rb_define_method(rb_cPGconn, "parameter_status", pgconn_parameter_status, 1);
4120
+ rb_define_method(rb_cPGconn, "protocol_version", pgconn_protocol_version, 0);
4121
+ rb_define_method(rb_cPGconn, "server_version", pgconn_server_version, 0);
4122
+ rb_define_method(rb_cPGconn, "error_message", pgconn_error_message, 0);
4123
+ rb_define_method(rb_cPGconn, "socket", pgconn_socket, 0);
4124
+ rb_define_method(rb_cPGconn, "socket_io", pgconn_socket_io, 0);
4125
+ rb_define_method(rb_cPGconn, "backend_pid", pgconn_backend_pid, 0);
4126
+ rb_define_method(rb_cPGconn, "connection_needs_password", pgconn_connection_needs_password, 0);
4127
+ rb_define_method(rb_cPGconn, "connection_used_password", pgconn_connection_used_password, 0);
4128
+ /* rb_define_method(rb_cPGconn, "getssl", pgconn_getssl, 0); */
4129
+
4130
+ /****** PG::Connection INSTANCE METHODS: Command Execution ******/
4131
+ rb_define_method(rb_cPGconn, "sync_exec", pgconn_exec, -1);
4132
+ rb_define_method(rb_cPGconn, "sync_exec_params", pgconn_exec_params, -1);
4133
+ rb_define_method(rb_cPGconn, "sync_prepare", pgconn_prepare, -1);
4134
+ rb_define_method(rb_cPGconn, "sync_exec_prepared", pgconn_exec_prepared, -1);
4135
+ rb_define_method(rb_cPGconn, "sync_describe_prepared", pgconn_describe_prepared, 1);
4136
+ rb_define_method(rb_cPGconn, "sync_describe_portal", pgconn_describe_portal, 1);
4137
+ rb_define_method(rb_cPGconn, "make_empty_pgresult", pgconn_make_empty_pgresult, 1);
4138
+ rb_define_method(rb_cPGconn, "escape_string", pgconn_s_escape, 1);
4139
+ rb_define_alias(rb_cPGconn, "escape", "escape_string");
4140
+ rb_define_method(rb_cPGconn, "escape_literal", pgconn_escape_literal, 1);
4141
+ rb_define_method(rb_cPGconn, "escape_identifier", pgconn_escape_identifier, 1);
4142
+ rb_define_method(rb_cPGconn, "escape_bytea", pgconn_s_escape_bytea, 1);
4143
+ rb_define_method(rb_cPGconn, "unescape_bytea", pgconn_s_unescape_bytea, 1);
4144
+ rb_define_method(rb_cPGconn, "set_single_row_mode", pgconn_set_single_row_mode, 0);
4145
+
4146
+ /****** PG::Connection INSTANCE METHODS: Asynchronous Command Processing ******/
4147
+ rb_define_method(rb_cPGconn, "send_query", pgconn_send_query, -1);
4148
+ rb_define_method(rb_cPGconn, "send_query_params", pgconn_send_query_params, -1);
4149
+ rb_define_method(rb_cPGconn, "async_exec", pgconn_async_exec, -1);
4150
+ rb_define_method(rb_cPGconn, "async_exec_params", pgconn_async_exec_params, -1);
4151
+ rb_define_alias(rb_cPGconn, "async_query", "async_exec");
4152
+ rb_define_method(rb_cPGconn, "send_prepare", pgconn_send_prepare, -1);
4153
+ rb_define_method(rb_cPGconn, "async_prepare", pgconn_async_prepare, -1);
4154
+ rb_define_method(rb_cPGconn, "send_query_prepared", pgconn_send_query_prepared, -1);
4155
+ rb_define_method(rb_cPGconn, "async_exec_prepared", pgconn_async_exec_prepared, -1);
4156
+ rb_define_method(rb_cPGconn, "send_describe_prepared", pgconn_send_describe_prepared, 1);
4157
+ rb_define_method(rb_cPGconn, "async_describe_prepared", pgconn_async_describe_prepared, 1);
4158
+ rb_define_method(rb_cPGconn, "send_describe_portal", pgconn_send_describe_portal, 1);
4159
+ rb_define_method(rb_cPGconn, "async_describe_portal", pgconn_async_describe_portal, 1);
4160
+ rb_define_method(rb_cPGconn, "get_result", pgconn_get_result, 0);
4161
+ rb_define_method(rb_cPGconn, "consume_input", pgconn_consume_input, 0);
4162
+ rb_define_method(rb_cPGconn, "is_busy", pgconn_is_busy, 0);
4163
+ rb_define_method(rb_cPGconn, "setnonblocking", pgconn_setnonblocking, 1);
4164
+ rb_define_method(rb_cPGconn, "isnonblocking", pgconn_isnonblocking, 0);
4165
+ rb_define_alias(rb_cPGconn, "nonblocking?", "isnonblocking");
4166
+ rb_define_method(rb_cPGconn, "flush", pgconn_flush, 0);
4167
+ rb_define_method(rb_cPGconn, "discard_results", pgconn_discard_results, 0);
4168
+
4169
+ /****** PG::Connection INSTANCE METHODS: Cancelling Queries in Progress ******/
4170
+ rb_define_method(rb_cPGconn, "cancel", pgconn_cancel, 0);
4171
+
4172
+ /****** PG::Connection INSTANCE METHODS: NOTIFY ******/
4173
+ rb_define_method(rb_cPGconn, "notifies", pgconn_notifies, 0);
4174
+
4175
+ /****** PG::Connection INSTANCE METHODS: COPY ******/
4176
+ rb_define_method(rb_cPGconn, "put_copy_data", pgconn_put_copy_data, -1);
4177
+ rb_define_method(rb_cPGconn, "put_copy_end", pgconn_put_copy_end, -1);
4178
+ rb_define_method(rb_cPGconn, "get_copy_data", pgconn_get_copy_data, -1);
4179
+
4180
+ /****** PG::Connection INSTANCE METHODS: Control Functions ******/
4181
+ rb_define_method(rb_cPGconn, "set_error_verbosity", pgconn_set_error_verbosity, 1);
4182
+ rb_define_method(rb_cPGconn, "trace", pgconn_trace, 1);
4183
+ rb_define_method(rb_cPGconn, "untrace", pgconn_untrace, 0);
4184
+ rb_define_method(rb_cPGconn, "guess_result_memsize=", pgconn_guess_result_memsize_set, 1);
4185
+
4186
+ /****** PG::Connection INSTANCE METHODS: Notice Processing ******/
4187
+ rb_define_method(rb_cPGconn, "set_notice_receiver", pgconn_set_notice_receiver, 0);
4188
+ rb_define_method(rb_cPGconn, "set_notice_processor", pgconn_set_notice_processor, 0);
4189
+
4190
+ /****** PG::Connection INSTANCE METHODS: Other ******/
4191
+ rb_define_method(rb_cPGconn, "get_client_encoding", pgconn_get_client_encoding, 0);
4192
+ rb_define_method(rb_cPGconn, "set_client_encoding", pgconn_set_client_encoding, 1);
4193
+ rb_define_alias(rb_cPGconn, "client_encoding=", "set_client_encoding");
4194
+ rb_define_method(rb_cPGconn, "transaction", pgconn_transaction, 0);
4195
+ rb_define_method(rb_cPGconn, "block", pgconn_block, -1);
4196
+ rb_define_method(rb_cPGconn, "wait_for_notify", pgconn_wait_for_notify, -1);
4197
+ rb_define_alias(rb_cPGconn, "notifies_wait", "wait_for_notify");
4198
+ rb_define_method(rb_cPGconn, "quote_ident", pgconn_s_quote_ident, 1);
4199
+ rb_define_method(rb_cPGconn, "get_last_result", pgconn_get_last_result, 0);
4200
+ #ifdef HAVE_PQENCRYPTPASSWORDCONN
4201
+ rb_define_method(rb_cPGconn, "encrypt_password", pgconn_encrypt_password, -1);
4202
+ #endif
4203
+
4204
+ #ifdef HAVE_PQSSLATTRIBUTE
4205
+ rb_define_method(rb_cPGconn, "ssl_in_use?", pgconn_ssl_in_use, 0);
4206
+ rb_define_method(rb_cPGconn, "ssl_attribute", pgconn_ssl_attribute, 1);
4207
+ rb_define_method(rb_cPGconn, "ssl_attribute_names", pgconn_ssl_attribute_names, 0);
4208
+ #endif
4209
+
4210
+ /****** PG::Connection INSTANCE METHODS: Large Object Support ******/
4211
+ rb_define_method(rb_cPGconn, "lo_creat", pgconn_locreat, -1);
4212
+ rb_define_alias(rb_cPGconn, "locreat", "lo_creat");
4213
+ rb_define_method(rb_cPGconn, "lo_create", pgconn_locreate, 1);
4214
+ rb_define_alias(rb_cPGconn, "locreate", "lo_create");
4215
+ rb_define_method(rb_cPGconn, "lo_import", pgconn_loimport, 1);
4216
+ rb_define_alias(rb_cPGconn, "loimport", "lo_import");
4217
+ rb_define_method(rb_cPGconn, "lo_export", pgconn_loexport, 2);
4218
+ rb_define_alias(rb_cPGconn, "loexport", "lo_export");
4219
+ rb_define_method(rb_cPGconn, "lo_open", pgconn_loopen, -1);
4220
+ rb_define_alias(rb_cPGconn, "loopen", "lo_open");
4221
+ rb_define_method(rb_cPGconn, "lo_write",pgconn_lowrite, 2);
4222
+ rb_define_alias(rb_cPGconn, "lowrite", "lo_write");
4223
+ rb_define_method(rb_cPGconn, "lo_read",pgconn_loread, 2);
4224
+ rb_define_alias(rb_cPGconn, "loread", "lo_read");
4225
+ rb_define_method(rb_cPGconn, "lo_lseek",pgconn_lolseek, 3);
4226
+ rb_define_alias(rb_cPGconn, "lolseek", "lo_lseek");
4227
+ rb_define_alias(rb_cPGconn, "lo_seek", "lo_lseek");
4228
+ rb_define_alias(rb_cPGconn, "loseek", "lo_lseek");
4229
+ rb_define_method(rb_cPGconn, "lo_tell",pgconn_lotell, 1);
4230
+ rb_define_alias(rb_cPGconn, "lotell", "lo_tell");
4231
+ rb_define_method(rb_cPGconn, "lo_truncate", pgconn_lotruncate, 2);
4232
+ rb_define_alias(rb_cPGconn, "lotruncate", "lo_truncate");
4233
+ rb_define_method(rb_cPGconn, "lo_close",pgconn_loclose, 1);
4234
+ rb_define_alias(rb_cPGconn, "loclose", "lo_close");
4235
+ rb_define_method(rb_cPGconn, "lo_unlink", pgconn_lounlink, 1);
4236
+ rb_define_alias(rb_cPGconn, "lounlink", "lo_unlink");
4237
+
4238
+ rb_define_method(rb_cPGconn, "internal_encoding", pgconn_internal_encoding, 0);
4239
+ rb_define_method(rb_cPGconn, "internal_encoding=", pgconn_internal_encoding_set, 1);
4240
+ rb_define_method(rb_cPGconn, "external_encoding", pgconn_external_encoding, 0);
4241
+ rb_define_method(rb_cPGconn, "set_default_encoding", pgconn_set_default_encoding, 0);
4242
+
4243
+ rb_define_method(rb_cPGconn, "type_map_for_queries=", pgconn_type_map_for_queries_set, 1);
4244
+ rb_define_method(rb_cPGconn, "type_map_for_queries", pgconn_type_map_for_queries_get, 0);
4245
+ rb_define_method(rb_cPGconn, "type_map_for_results=", pgconn_type_map_for_results_set, 1);
4246
+ rb_define_method(rb_cPGconn, "type_map_for_results", pgconn_type_map_for_results_get, 0);
4247
+ rb_define_method(rb_cPGconn, "encoder_for_put_copy_data=", pgconn_encoder_for_put_copy_data_set, 1);
4248
+ rb_define_method(rb_cPGconn, "encoder_for_put_copy_data", pgconn_encoder_for_put_copy_data_get, 0);
4249
+ rb_define_method(rb_cPGconn, "decoder_for_get_copy_data=", pgconn_decoder_for_get_copy_data_set, 1);
4250
+ rb_define_method(rb_cPGconn, "decoder_for_get_copy_data", pgconn_decoder_for_get_copy_data_get, 0);
4251
+ }
4252
+