yugabytedb-ysql 0.3

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