autocompl 0.2.1 → 0.2.2

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