pg 1.6.0.rc2-aarch64-linux

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