pg 0.12.0 → 0.16.0

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