jruby-pg 0.1-java

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