jruby-pg 0.1-java

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. checksums.yaml +7 -0
  2. data/.gemtest +0 -0
  3. data/BSDL +22 -0
  4. data/ChangeLog +0 -0
  5. data/Contributors.rdoc +45 -0
  6. data/History.rdoc +270 -0
  7. data/LICENSE +56 -0
  8. data/Manifest.txt +44 -0
  9. data/POSTGRES +23 -0
  10. data/README-OS_X.rdoc +68 -0
  11. data/README-Windows.rdoc +67 -0
  12. data/README.ja.rdoc +14 -0
  13. data/README.rdoc +102 -0
  14. data/Rakefile +211 -0
  15. data/Rakefile.cross +273 -0
  16. data/ext/gvl_wrappers.c +13 -0
  17. data/ext/pg.c +545 -0
  18. data/ext/pg_connection.c +3643 -0
  19. data/ext/pg_errors.c +89 -0
  20. data/ext/pg_result.c +920 -0
  21. data/lib/pg.rb +52 -0
  22. data/lib/pg/connection.rb +179 -0
  23. data/lib/pg/constants.rb +11 -0
  24. data/lib/pg/exceptions.rb +11 -0
  25. data/lib/pg/result.rb +16 -0
  26. data/lib/pg_ext.jar +0 -0
  27. data/sample/array_insert.rb +20 -0
  28. data/sample/async_api.rb +106 -0
  29. data/sample/async_copyto.rb +39 -0
  30. data/sample/async_mixed.rb +56 -0
  31. data/sample/check_conn.rb +21 -0
  32. data/sample/copyfrom.rb +81 -0
  33. data/sample/copyto.rb +19 -0
  34. data/sample/cursor.rb +21 -0
  35. data/sample/disk_usage_report.rb +186 -0
  36. data/sample/issue-119.rb +94 -0
  37. data/sample/losample.rb +69 -0
  38. data/sample/minimal-testcase.rb +17 -0
  39. data/sample/notify_wait.rb +72 -0
  40. data/sample/pg_statistics.rb +294 -0
  41. data/sample/replication_monitor.rb +231 -0
  42. data/sample/test_binary_values.rb +33 -0
  43. data/sample/wal_shipper.rb +434 -0
  44. data/sample/warehouse_partitions.rb +320 -0
  45. data/spec/data/expected_trace.out +26 -0
  46. data/spec/data/random_binary_data +0 -0
  47. data/spec/lib/helpers.rb +350 -0
  48. data/spec/pg/connection_spec.rb +1276 -0
  49. data/spec/pg/result_spec.rb +345 -0
  50. data/spec/pg_spec.rb +44 -0
  51. metadata +190 -0
@@ -0,0 +1,273 @@
1
+ #!/usr/bin/env rake
2
+
3
+ require 'uri'
4
+ require 'tempfile'
5
+ require 'rbconfig'
6
+ require 'rake/clean'
7
+ require 'rake/extensiontask'
8
+ require 'rake/extensioncompiler'
9
+ require 'ostruct'
10
+
11
+ MISCDIR = BASEDIR + 'misc'
12
+
13
+ NUM_CPUS = if File.exist?('/proc/cpuinfo')
14
+ File.read('/proc/cpuinfo').scan('processor').length
15
+ elsif RUBY_PLATFORM.include?( 'darwin' )
16
+ `system_profiler SPHardwareDataType | grep 'Cores' | awk '{print $5}'`.chomp
17
+ else
18
+ 1
19
+ end
20
+
21
+ class CrossLibrary < OpenStruct
22
+ include Rake::DSL
23
+
24
+ def initialize(for_platform, openssl_config)
25
+ super()
26
+
27
+ self.for_platform = for_platform
28
+ self.openssl_config = openssl_config
29
+
30
+ # Cross-compilation constants
31
+ self.openssl_version = ENV['OPENSSL_VERSION'] || '1.0.1e'
32
+ self.postgresql_version = ENV['POSTGRESQL_VERSION'] || '9.2.3'
33
+
34
+ self.compile_home = Pathname( "./build" ).expand_path
35
+ self.static_sourcesdir = compile_home + 'sources'
36
+ self.static_builddir = compile_home + 'builds' + for_platform
37
+
38
+ # Static OpenSSL build vars
39
+ self.static_openssl_builddir = static_builddir + "openssl-#{openssl_version}"
40
+
41
+ self.openssl_source_uri =
42
+ URI( "http://www.openssl.org/source/openssl-#{openssl_version}.tar.gz" )
43
+ self.openssl_tarball = static_sourcesdir + File.basename( openssl_source_uri.path )
44
+ self.openssl_makefile = static_openssl_builddir + 'Makefile'
45
+
46
+ self.libssleay32 = static_openssl_builddir + 'libssleay32.a'
47
+ self.libeay32 = static_openssl_builddir + 'libeay32.a'
48
+
49
+ self.openssl_patches = Rake::FileList[ (MISCDIR + "openssl-#{openssl_version}.*.patch").to_s ]
50
+
51
+ # Static PostgreSQL build vars
52
+ self.static_postgresql_builddir = static_builddir + "postgresql-#{postgresql_version}"
53
+ self.postgresql_source_uri = begin
54
+ uristring = "http://ftp.postgresql.org/pub/source/v%s/postgresql-%s.tar.bz2" %
55
+ [ postgresql_version, postgresql_version ]
56
+ URI( uristring )
57
+ end
58
+ self.postgresql_tarball = static_sourcesdir + File.basename( postgresql_source_uri.path )
59
+
60
+ self.static_postgresql_srcdir = static_postgresql_builddir + 'src'
61
+ self.static_postgresql_libdir = static_postgresql_srcdir + 'interfaces/libpq'
62
+ self.static_postgresql_incdir = static_postgresql_srcdir + 'include'
63
+
64
+ self.postgresql_global_makefile = static_postgresql_srcdir + 'Makefile.global'
65
+ self.postgresql_shlib_makefile = static_postgresql_srcdir + 'Makefile.shlib'
66
+ self.postgresql_shlib_mf_orig = static_postgresql_srcdir + 'Makefile.shlib.orig'
67
+ self.postgresql_lib = static_postgresql_libdir + 'libpq.a'
68
+ self.postgresql_patches = Rake::FileList[ (MISCDIR + "postgresql-#{postgresql_version}.*.patch").to_s ]
69
+
70
+ # Use rake-compilers config.yml to determine the toolchain that was used
71
+ # to build Ruby for this platform.
72
+ self.host_platform = begin
73
+ config_file = YAML.load_file(File.expand_path("~/.rake-compiler/config.yml"))
74
+ _, rbfile = config_file.find{|key, fname| key.start_with?("rbconfig-#{for_platform}-") }
75
+ IO.read(rbfile).match(/CONFIG\["CC"\] = "(.*)"/)[1].sub(/\-gcc/, '')
76
+ rescue
77
+ nil
78
+ end
79
+
80
+
81
+ # clean intermediate files and folders
82
+ CLEAN.include( static_builddir.to_s )
83
+
84
+
85
+ ENV['RUBY_CC_VERSION'] ||= '1.8.7:1.9.3:2.0.0'
86
+
87
+ def download(url, save_to)
88
+ part = save_to+".part"
89
+ sh "wget #{url.to_s.inspect} -O #{part.inspect} || curl #{url.to_s.inspect} -o #{part.inspect}"
90
+ FileUtils.mv part, save_to
91
+ end
92
+
93
+ def run(*args)
94
+ sh *args
95
+ end
96
+
97
+ #####################################################################
98
+ ### C R O S S - C O M P I L A T I O N - T A S K S
99
+ #####################################################################
100
+
101
+
102
+ directory static_sourcesdir.to_s
103
+
104
+ #
105
+ # Static OpenSSL build tasks
106
+ #
107
+ directory static_openssl_builddir.to_s
108
+
109
+ # openssl source file should be stored there
110
+ file openssl_tarball => static_sourcesdir do |t|
111
+ download( openssl_source_uri, t.name )
112
+ end
113
+
114
+ # Extract the openssl builds
115
+ file static_openssl_builddir => openssl_tarball do |t|
116
+ puts "extracting %s to %s" % [ openssl_tarball, static_openssl_builddir.parent ]
117
+ static_openssl_builddir.mkpath
118
+ run 'tar', '-xzf', openssl_tarball.to_s, '-C', static_openssl_builddir.parent.to_s
119
+ openssl_makefile.unlink if openssl_makefile.exist?
120
+
121
+ openssl_patches.each do |patchfile|
122
+ puts " applying patch #{patchfile}..."
123
+ run 'patch', '-Np1', '-d', static_openssl_builddir.to_s,
124
+ '-i', File.expand_path( patchfile, BASEDIR )
125
+ end
126
+ end
127
+
128
+ self.cmd_prelude = [
129
+ 'env',
130
+ "CC=#{host_platform}-gcc",
131
+ "CFLAGS=-DDSO_WIN32",
132
+ "AR=#{host_platform}-ar",
133
+ "RANLIB=#{host_platform}-ranlib"
134
+ ]
135
+
136
+
137
+ # generate the makefile in a clean build location
138
+ file openssl_makefile => static_openssl_builddir do |t|
139
+ Dir.chdir( static_openssl_builddir ) do
140
+ cmd = cmd_prelude.dup
141
+ cmd << "./Configure" << openssl_config
142
+
143
+ run( *cmd )
144
+ end
145
+ end
146
+
147
+ desc "compile static openssl libraries"
148
+ task :openssl_libs => [ libssleay32, libeay32 ]
149
+
150
+ task :compile_static_openssl => openssl_makefile do |t|
151
+ Dir.chdir( static_openssl_builddir ) do
152
+ cmd = cmd_prelude.dup
153
+ cmd << 'make' << "-j#{NUM_CPUS}" << 'build_libs'
154
+
155
+ run( *cmd )
156
+ end
157
+ end
158
+
159
+ desc "compile static #{libeay32}"
160
+ file libeay32 => :compile_static_openssl do |t|
161
+ FileUtils.cp( static_openssl_builddir + 'libcrypto.a', libeay32.to_s )
162
+ end
163
+
164
+ desc "compile static #{libssleay32}"
165
+ file libssleay32 => :compile_static_openssl do |t|
166
+ FileUtils.cp( static_openssl_builddir + 'libssl.a', libssleay32.to_s )
167
+ end
168
+
169
+
170
+
171
+ #
172
+ # Static PostgreSQL build tasks
173
+ #
174
+ directory static_postgresql_builddir.to_s
175
+
176
+
177
+ # postgresql source file should be stored there
178
+ file postgresql_tarball => static_sourcesdir do |t|
179
+ download( postgresql_source_uri, t.name )
180
+ end
181
+
182
+ # Extract the postgresql sources
183
+ file static_postgresql_builddir => postgresql_tarball do |t|
184
+ puts "extracting %s to %s" % [ postgresql_tarball, static_postgresql_builddir.parent ]
185
+ static_postgresql_builddir.mkpath
186
+ run 'tar', '-xjf', postgresql_tarball.to_s, '-C', static_postgresql_builddir.parent.to_s
187
+ mv postgresql_shlib_makefile, postgresql_shlib_mf_orig
188
+
189
+ postgresql_patches.each do |patchfile|
190
+ puts " applying patch #{patchfile}..."
191
+ run 'patch', '-Np1', '-d', static_postgresql_builddir.to_s,
192
+ '-i', File.expand_path( patchfile, BASEDIR )
193
+ end
194
+ end
195
+
196
+ # generate the makefile in a clean build location
197
+ file postgresql_global_makefile => [ static_postgresql_builddir, :openssl_libs ] do |t|
198
+ options = [
199
+ "--target=#{host_platform}",
200
+ "--host=#{host_platform}",
201
+ '--with-openssl',
202
+ '--without-zlib',
203
+ '--disable-shared',
204
+ ]
205
+
206
+ Dir.chdir( static_postgresql_builddir ) do
207
+ configure_path = static_postgresql_builddir + 'configure'
208
+ cmd = [ configure_path.to_s, *options ]
209
+ cmd << "CFLAGS=-L#{static_openssl_builddir}"
210
+ cmd << "LDFLAGS=-L#{static_openssl_builddir}"
211
+ cmd << "LDFLAGS_SL=-L#{static_openssl_builddir}"
212
+ cmd << "LIBS=-lwsock32 -lgdi32"
213
+ cmd << "CPPFLAGS=-I#{static_openssl_builddir}/include"
214
+
215
+ run( *cmd )
216
+ end
217
+ end
218
+
219
+
220
+ # patch the Makefile.shlib -- depend on the build dir so it's only
221
+ # rewritten if the tarball is re-extracted.
222
+ file postgresql_shlib_makefile => postgresql_shlib_mf_orig do |t|
223
+ tf = Tempfile.new( postgresql_shlib_makefile.basename.to_s )
224
+ postgresql_shlib_mf_orig.open( File::RDONLY ) do |ifh|
225
+ ifh.each_line do |line|
226
+ tf.print( line.sub(/^(\s*haslibarule\s*=\s*yes)/, "# \\1 ") )
227
+ end
228
+ end
229
+ tf.close
230
+
231
+ FileUtils.mv( tf.path, t.name, :verbose => $puts )
232
+ end
233
+
234
+
235
+ # make libpq.a
236
+ task postgresql_lib => [ postgresql_global_makefile, postgresql_shlib_makefile ] do |t|
237
+ Dir.chdir( postgresql_lib.dirname ) do
238
+ sh 'make', "-j#{NUM_CPUS}", postgresql_lib.basename.to_s, 'PORTNAME=win32'
239
+ end
240
+ end
241
+
242
+
243
+ #desc 'compile static libpg.a'
244
+ task :static_libpq => postgresql_lib
245
+ end
246
+ end
247
+
248
+ if File.exist?(File.expand_path("~/.rake-compiler/config.yml"))
249
+ CrossLibraries = [
250
+ ['i386-mingw32', 'mingw'],
251
+ ['x64-mingw32', 'mingw64'],
252
+ ].map do |platform, openssl_config|
253
+ CrossLibrary.new platform, openssl_config
254
+ end
255
+ else
256
+ $stderr.puts "Cross-compilation disabled -- rake-compiler not properly installed"
257
+ CrossLibraries = []
258
+ end
259
+
260
+ desc 'cross compile pg for win32'
261
+ task :cross do
262
+ ENV['CROSS_COMPILING'] = 'yes'
263
+ end
264
+ task :cross => [ :mingw32, :static_libpq ]
265
+
266
+ task :mingw32 do
267
+ # Use Rake::ExtensionCompiler helpers to find the proper host
268
+ unless Rake::ExtensionCompiler.mingw_host then
269
+ warn "You need to install mingw32 cross compile functionality to be able to continue."
270
+ warn "Please refer to your distribution/package manager documentation about installation."
271
+ fail
272
+ end
273
+ end
@@ -0,0 +1,13 @@
1
+ /*
2
+ * gvl_wrappers.c - Wrapper functions for locking/unlocking the Ruby GVL
3
+ *
4
+ */
5
+
6
+ #include "pg.h"
7
+
8
+ FOR_EACH_BLOCKING_FUNCTION( DEFINE_GVL_WRAPPER_STRUCT );
9
+ FOR_EACH_BLOCKING_FUNCTION( DEFINE_GVL_SKELETON );
10
+ FOR_EACH_BLOCKING_FUNCTION( DEFINE_GVL_STUB );
11
+ FOR_EACH_CALLBACK_FUNCTION( DEFINE_GVL_WRAPPER_STRUCT );
12
+ FOR_EACH_CALLBACK_FUNCTION( DEFINE_GVLCB_SKELETON );
13
+ FOR_EACH_CALLBACK_FUNCTION( DEFINE_GVLCB_STUB );
@@ -0,0 +1,545 @@
1
+ /*
2
+ * pg.c - Toplevel extension
3
+ * $Id$
4
+ *
5
+ * Author/s:
6
+ *
7
+ * - Jeff Davis <ruby-pg@j-davis.com>
8
+ * - Guy Decoux (ts) <decoux@moulon.inra.fr>
9
+ * - Michael Granger <ged@FaerieMUD.org>
10
+ * - Dave Lee
11
+ * - Eiji Matsumoto <usagi@ruby.club.or.jp>
12
+ * - Yukihiro Matsumoto <matz@ruby-lang.org>
13
+ * - Noboru Saitou <noborus@netlab.jp>
14
+ *
15
+ * See Contributors.rdoc for the many additional fine people that have contributed
16
+ * to this library over the years.
17
+ *
18
+ * Copyright (c) 1997-2012 by the authors.
19
+ *
20
+ * You may redistribute this software under the same terms as Ruby itself; see
21
+ * http://www.ruby-lang.org/en/LICENSE.txt or the LICENSE file in the source
22
+ * for details.
23
+ *
24
+ * Portions of the code are from the PostgreSQL project, and are distributed
25
+ * under the terms of the PostgreSQL license, included in the file "POSTGRES".
26
+ *
27
+ * Portions copyright LAIKA, Inc.
28
+ *
29
+ *
30
+ * The following functions are part of libpq, but not available from ruby-pg,
31
+ * because they are deprecated, obsolete, or generally not useful:
32
+ *
33
+ * - PQfreemem -- unnecessary: copied to ruby object, then freed. Ruby object's
34
+ * memory is freed when it is garbage collected.
35
+ * - PQbinaryTuples -- better to use PQfformat
36
+ * - PQprint -- not very useful
37
+ * - PQsetdb -- not very useful
38
+ * - PQoidStatus -- deprecated, use PQoidValue
39
+ * - PQrequestCancel -- deprecated, use PQcancel
40
+ * - PQfn -- use a prepared statement instead
41
+ * - PQgetline -- deprecated, use PQgetCopyData
42
+ * - PQgetlineAsync -- deprecated, use PQgetCopyData
43
+ * - PQputline -- deprecated, use PQputCopyData
44
+ * - PQputnbytes -- deprecated, use PQputCopyData
45
+ * - PQendcopy -- deprecated, use PQputCopyEnd
46
+ */
47
+
48
+ #include "pg.h"
49
+
50
+ VALUE rb_mPG;
51
+ VALUE rb_mPGconstants;
52
+
53
+
54
+ /*
55
+ * Document-class: PG::Error
56
+ *
57
+ * This is the exception class raised when an error is returned from
58
+ * a libpq API call.
59
+ *
60
+ * The attributes +connection+ and +result+ are set to the connection
61
+ * object and result set object, respectively.
62
+ *
63
+ * If the connection object or result set object is not available from
64
+ * the context in which the error was encountered, it is +nil+.
65
+ */
66
+
67
+ /*
68
+ * M17n functions
69
+ */
70
+
71
+ #ifdef M17N_SUPPORTED
72
+ /**
73
+ * The mapping from canonical encoding names in PostgreSQL to ones in Ruby.
74
+ */
75
+ const char * const (pg_enc_pg2ruby_mapping[][2]) = {
76
+ {"BIG5", "Big5" },
77
+ {"EUC_CN", "GB2312" },
78
+ {"EUC_JP", "EUC-JP" },
79
+ {"EUC_JIS_2004", "EUC-JP" },
80
+ {"EUC_KR", "EUC-KR" },
81
+ {"EUC_TW", "EUC-TW" },
82
+ {"GB18030", "GB18030" },
83
+ {"GBK", "GBK" },
84
+ {"ISO_8859_5", "ISO-8859-5" },
85
+ {"ISO_8859_6", "ISO-8859-6" },
86
+ {"ISO_8859_7", "ISO-8859-7" },
87
+ {"ISO_8859_8", "ISO-8859-8" },
88
+ /* {"JOHAB", "JOHAB" }, dummy */
89
+ {"KOI8", "KOI8-R" },
90
+ {"KOI8R", "KOI8-R" },
91
+ {"KOI8U", "KOI8-U" },
92
+ {"LATIN1", "ISO-8859-1" },
93
+ {"LATIN2", "ISO-8859-2" },
94
+ {"LATIN3", "ISO-8859-3" },
95
+ {"LATIN4", "ISO-8859-4" },
96
+ {"LATIN5", "ISO-8859-9" },
97
+ {"LATIN6", "ISO-8859-10" },
98
+ {"LATIN7", "ISO-8859-13" },
99
+ {"LATIN8", "ISO-8859-14" },
100
+ {"LATIN9", "ISO-8859-15" },
101
+ {"LATIN10", "ISO-8859-16" },
102
+ {"MULE_INTERNAL", "Emacs-Mule" },
103
+ {"SJIS", "Windows-31J" },
104
+ {"SHIFT_JIS_2004","Windows-31J" },
105
+ /* {"SQL_ASCII", NULL }, special case*/
106
+ {"UHC", "CP949" },
107
+ {"UTF8", "UTF-8" },
108
+ {"WIN866", "IBM866" },
109
+ {"WIN874", "Windows-874" },
110
+ {"WIN1250", "Windows-1250"},
111
+ {"WIN1251", "Windows-1251"},
112
+ {"WIN1252", "Windows-1252"},
113
+ {"WIN1253", "Windows-1253"},
114
+ {"WIN1254", "Windows-1254"},
115
+ {"WIN1255", "Windows-1255"},
116
+ {"WIN1256", "Windows-1256"},
117
+ {"WIN1257", "Windows-1257"},
118
+ {"WIN1258", "Windows-1258"}
119
+ };
120
+
121
+
122
+ /*
123
+ * A cache of mapping from PostgreSQL's encoding indices to Ruby's rb_encoding*s.
124
+ */
125
+ static struct st_table *enc_pg2ruby;
126
+ static ID s_id_index;
127
+
128
+
129
+ /*
130
+ * Get the index of encoding +val+.
131
+ * :FIXME: Look into replacing this with rb_enc_get_index() since 1.9.1 isn't really
132
+ * used anymore.
133
+ */
134
+ int
135
+ pg_enc_get_index(VALUE val)
136
+ {
137
+ int i = ENCODING_GET_INLINED(val);
138
+ if (i == ENCODING_INLINE_MAX) {
139
+ VALUE iv = rb_ivar_get(val, s_id_index);
140
+ i = NUM2INT(iv);
141
+ }
142
+ return i;
143
+ }
144
+
145
+
146
+ /*
147
+ * Look up the JOHAB encoding, creating it as a dummy encoding if it's not
148
+ * already defined.
149
+ */
150
+ static rb_encoding *
151
+ pg_find_or_create_johab(void)
152
+ {
153
+ static const char * const aliases[] = { "JOHAB", "Windows-1361", "CP1361" };
154
+ int enc_index;
155
+ size_t i;
156
+
157
+ for (i = 0; i < sizeof(aliases)/sizeof(aliases[0]); ++i) {
158
+ enc_index = rb_enc_find_index(aliases[i]);
159
+ if (enc_index > 0) return rb_enc_from_index(enc_index);
160
+ }
161
+
162
+ enc_index = rb_define_dummy_encoding(aliases[0]);
163
+ for (i = 1; i < sizeof(aliases)/sizeof(aliases[0]); ++i) {
164
+ ENC_ALIAS(aliases[i], aliases[0]);
165
+ }
166
+ return rb_enc_from_index(enc_index);
167
+ }
168
+
169
+ /*
170
+ * Return the given PostgreSQL encoding ID as an rb_encoding.
171
+ *
172
+ * - returns NULL if the client encoding is 'SQL_ASCII'.
173
+ * - returns ASCII-8BIT if the client encoding is unknown.
174
+ */
175
+ rb_encoding *
176
+ pg_get_pg_encoding_as_rb_encoding( int enc_id )
177
+ {
178
+ rb_encoding *enc;
179
+
180
+ /* Use the cached value if it exists */
181
+ if ( st_lookup(enc_pg2ruby, (st_data_t)enc_id, (st_data_t*)&enc) ) {
182
+ return enc;
183
+ }
184
+ else {
185
+ const char *name = pg_encoding_to_char( enc_id );
186
+
187
+ enc = pg_get_pg_encname_as_rb_encoding( name );
188
+ st_insert( enc_pg2ruby, (st_data_t)enc_id, (st_data_t)enc );
189
+
190
+ return enc;
191
+ }
192
+
193
+ }
194
+
195
+ /*
196
+ * Return the given PostgreSQL encoding name as an rb_encoding.
197
+ */
198
+ rb_encoding *
199
+ pg_get_pg_encname_as_rb_encoding( const char *pg_encname )
200
+ {
201
+ size_t i;
202
+
203
+ /* Trying looking it up in the conversion table */
204
+ for ( i = 0; i < sizeof(pg_enc_pg2ruby_mapping)/sizeof(pg_enc_pg2ruby_mapping[0]); ++i ) {
205
+ if ( strcmp(pg_encname, pg_enc_pg2ruby_mapping[i][0]) == 0 )
206
+ return rb_enc_find( pg_enc_pg2ruby_mapping[i][1] );
207
+ }
208
+
209
+ /* JOHAB isn't a builtin encoding, so make up a dummy encoding if it's seen */
210
+ if ( strncmp(pg_encname, "JOHAB", 5) == 0 )
211
+ return pg_find_or_create_johab();
212
+
213
+ /* Fallthrough to ASCII-8BIT */
214
+ return rb_ascii8bit_encoding();
215
+ }
216
+
217
+ /*
218
+ * Get the client encoding of the specified connection handle and return it as a rb_encoding.
219
+ */
220
+ rb_encoding *
221
+ pg_conn_enc_get( PGconn *conn )
222
+ {
223
+ int enc_id = PQclientEncoding( conn );
224
+ return pg_get_pg_encoding_as_rb_encoding( enc_id );
225
+ }
226
+
227
+
228
+ /*
229
+ * Returns the given rb_encoding as the equivalent PostgreSQL encoding string.
230
+ */
231
+ const char *
232
+ pg_get_rb_encoding_as_pg_encoding( rb_encoding *enc )
233
+ {
234
+ const char *rb_encname = rb_enc_name( enc );
235
+ const char *encname = NULL;
236
+ size_t i;
237
+
238
+ for (i = 0; i < sizeof(pg_enc_pg2ruby_mapping)/sizeof(pg_enc_pg2ruby_mapping[0]); ++i) {
239
+ if (strcmp(rb_encname, pg_enc_pg2ruby_mapping[i][1]) == 0) {
240
+ encname = pg_enc_pg2ruby_mapping[i][0];
241
+ }
242
+ }
243
+
244
+ if ( !encname ) encname = "SQL_ASCII";
245
+
246
+ return encname;
247
+ }
248
+
249
+ #endif /* M17N_SUPPORTED */
250
+
251
+
252
+ /**************************************************************************
253
+ * Module Methods
254
+ **************************************************************************/
255
+
256
+ #ifdef HAVE_PQLIBVERSION
257
+ /*
258
+ * call-seq:
259
+ * PG.library_version -> Integer
260
+ *
261
+ * Get the version of the libpq library in use. The number is formed by
262
+ * converting the major, minor, and revision numbers into two-decimal-
263
+ * digit numbers and appending them together.
264
+ * For example, version 7.4.2 will be returned as 70402, and version
265
+ * 8.1 will be returned as 80100 (leading zeroes are not shown). Zero
266
+ * is returned if the connection is bad.
267
+ */
268
+ static VALUE
269
+ pg_s_library_version(VALUE self)
270
+ {
271
+ UNUSED( self );
272
+ return INT2NUM(PQlibVersion());
273
+ }
274
+ #endif
275
+
276
+
277
+ /*
278
+ * call-seq:
279
+ * PG.isthreadsafe -> Boolean
280
+ * PG.is_threadsafe? -> Boolean
281
+ * PG.threadsafe? -> Boolean
282
+ *
283
+ * Returns +true+ if libpq is thread-safe, +false+ otherwise.
284
+ */
285
+ static VALUE
286
+ pg_s_threadsafe_p(VALUE self)
287
+ {
288
+ UNUSED( self );
289
+ return PQisthreadsafe() ? Qtrue : Qfalse;
290
+ }
291
+
292
+
293
+
294
+ /**************************************************************************
295
+ * Initializer
296
+ **************************************************************************/
297
+
298
+ void
299
+ Init_pg_ext()
300
+ {
301
+ rb_mPG = rb_define_module( "PG" );
302
+ rb_mPGconstants = rb_define_module_under( rb_mPG, "Constants" );
303
+
304
+ /*************************
305
+ * PG module methods
306
+ *************************/
307
+ #ifdef HAVE_PQLIBVERSION
308
+ rb_define_singleton_method( rb_mPG, "library_version", pg_s_library_version, 0 );
309
+ #endif
310
+ rb_define_singleton_method( rb_mPG, "isthreadsafe", pg_s_threadsafe_p, 0 );
311
+ SINGLETON_ALIAS( rb_mPG, "is_threadsafe?", "isthreadsafe" );
312
+ SINGLETON_ALIAS( rb_mPG, "threadsafe?", "isthreadsafe" );
313
+
314
+ /****** PG::Connection CLASS CONSTANTS: Connection Status ******/
315
+
316
+ /* Connection succeeded */
317
+ rb_define_const(rb_mPGconstants, "CONNECTION_OK", INT2FIX(CONNECTION_OK));
318
+ /* Connection failed */
319
+ rb_define_const(rb_mPGconstants, "CONNECTION_BAD", INT2FIX(CONNECTION_BAD));
320
+
321
+ /****** PG::Connection CLASS CONSTANTS: Nonblocking connection status ******/
322
+
323
+ /* Waiting for connection to be made. */
324
+ rb_define_const(rb_mPGconstants, "CONNECTION_STARTED", INT2FIX(CONNECTION_STARTED));
325
+ /* Connection OK; waiting to send. */
326
+ rb_define_const(rb_mPGconstants, "CONNECTION_MADE", INT2FIX(CONNECTION_MADE));
327
+ /* Waiting for a response from the server. */
328
+ rb_define_const(rb_mPGconstants, "CONNECTION_AWAITING_RESPONSE", INT2FIX(CONNECTION_AWAITING_RESPONSE));
329
+ /* Received authentication; waiting for backend start-up to finish. */
330
+ rb_define_const(rb_mPGconstants, "CONNECTION_AUTH_OK", INT2FIX(CONNECTION_AUTH_OK));
331
+ /* Negotiating SSL encryption. */
332
+ rb_define_const(rb_mPGconstants, "CONNECTION_SSL_STARTUP", INT2FIX(CONNECTION_SSL_STARTUP));
333
+ /* Negotiating environment-driven parameter settings. */
334
+ rb_define_const(rb_mPGconstants, "CONNECTION_SETENV", INT2FIX(CONNECTION_SETENV));
335
+ /* Internal state: connect() needed. */
336
+ rb_define_const(rb_mPGconstants, "CONNECTION_NEEDED", INT2FIX(CONNECTION_NEEDED));
337
+
338
+ /****** PG::Connection CLASS CONSTANTS: Nonblocking connection polling status ******/
339
+
340
+ /* Async connection is waiting to read */
341
+ rb_define_const(rb_mPGconstants, "PGRES_POLLING_READING", INT2FIX(PGRES_POLLING_READING));
342
+ /* Async connection is waiting to write */
343
+ rb_define_const(rb_mPGconstants, "PGRES_POLLING_WRITING", INT2FIX(PGRES_POLLING_WRITING));
344
+ /* Async connection failed or was reset */
345
+ rb_define_const(rb_mPGconstants, "PGRES_POLLING_FAILED", INT2FIX(PGRES_POLLING_FAILED));
346
+ /* Async connection succeeded */
347
+ rb_define_const(rb_mPGconstants, "PGRES_POLLING_OK", INT2FIX(PGRES_POLLING_OK));
348
+
349
+ /****** PG::Connection CLASS CONSTANTS: Transaction Status ******/
350
+
351
+ /* Transaction is currently idle (#transaction_status) */
352
+ rb_define_const(rb_mPGconstants, "PQTRANS_IDLE", INT2FIX(PQTRANS_IDLE));
353
+ /* Transaction is currently active; query has been sent to the server, but not yet completed. (#transaction_status) */
354
+ rb_define_const(rb_mPGconstants, "PQTRANS_ACTIVE", INT2FIX(PQTRANS_ACTIVE));
355
+ /* Transaction is currently idle, in a valid transaction block (#transaction_status) */
356
+ rb_define_const(rb_mPGconstants, "PQTRANS_INTRANS", INT2FIX(PQTRANS_INTRANS));
357
+ /* Transaction is currently idle, in a failed transaction block (#transaction_status) */
358
+ rb_define_const(rb_mPGconstants, "PQTRANS_INERROR", INT2FIX(PQTRANS_INERROR));
359
+ /* Transaction's connection is bad (#transaction_status) */
360
+ rb_define_const(rb_mPGconstants, "PQTRANS_UNKNOWN", INT2FIX(PQTRANS_UNKNOWN));
361
+
362
+ /****** PG::Connection CLASS CONSTANTS: Error Verbosity ******/
363
+
364
+ /* Terse error verbosity level (#set_error_verbosity) */
365
+ rb_define_const(rb_mPGconstants, "PQERRORS_TERSE", INT2FIX(PQERRORS_TERSE));
366
+ /* Default error verbosity level (#set_error_verbosity) */
367
+ rb_define_const(rb_mPGconstants, "PQERRORS_DEFAULT", INT2FIX(PQERRORS_DEFAULT));
368
+ /* Verbose error verbosity level (#set_error_verbosity) */
369
+ rb_define_const(rb_mPGconstants, "PQERRORS_VERBOSE", INT2FIX(PQERRORS_VERBOSE));
370
+
371
+ #ifdef HAVE_PQPING
372
+ /****** PG::Connection CLASS CONSTANTS: Check Server Status ******/
373
+
374
+ /* Server is accepting connections. */
375
+ rb_define_const(rb_mPGconstants, "PQPING_OK", INT2FIX(PQPING_OK));
376
+ /* Server is alive but rejecting connections. */
377
+ rb_define_const(rb_mPGconstants, "PQPING_REJECT", INT2FIX(PQPING_REJECT));
378
+ /* Could not establish connection. */
379
+ rb_define_const(rb_mPGconstants, "PQPING_NO_RESPONSE", INT2FIX(PQPING_NO_RESPONSE));
380
+ /* Connection not attempted (bad params). */
381
+ rb_define_const(rb_mPGconstants, "PQPING_NO_ATTEMPT", INT2FIX(PQPING_NO_ATTEMPT));
382
+ #endif
383
+
384
+ /****** PG::Connection CLASS CONSTANTS: Large Objects ******/
385
+
386
+ /* Flag for #lo_creat, #lo_open -- open for writing */
387
+ rb_define_const(rb_mPGconstants, "INV_WRITE", INT2FIX(INV_WRITE));
388
+ /* Flag for #lo_creat, #lo_open -- open for reading */
389
+ rb_define_const(rb_mPGconstants, "INV_READ", INT2FIX(INV_READ));
390
+ /* Flag for #lo_lseek -- seek from object start */
391
+ rb_define_const(rb_mPGconstants, "SEEK_SET", INT2FIX(SEEK_SET));
392
+ /* Flag for #lo_lseek -- seek from current position */
393
+ rb_define_const(rb_mPGconstants, "SEEK_CUR", INT2FIX(SEEK_CUR));
394
+ /* Flag for #lo_lseek -- seek from object end */
395
+ rb_define_const(rb_mPGconstants, "SEEK_END", INT2FIX(SEEK_END));
396
+
397
+ /****** PG::Result CONSTANTS: result status ******/
398
+
399
+ /* #result_status constant: The string sent to the server was empty. */
400
+ rb_define_const(rb_mPGconstants, "PGRES_EMPTY_QUERY", INT2FIX(PGRES_EMPTY_QUERY));
401
+ /* #result_status constant: Successful completion of a command returning no data. */
402
+ rb_define_const(rb_mPGconstants, "PGRES_COMMAND_OK", INT2FIX(PGRES_COMMAND_OK));
403
+ /* #result_status constant: Successful completion of a command returning data
404
+ (such as a SELECT or SHOW). */
405
+ rb_define_const(rb_mPGconstants, "PGRES_TUPLES_OK", INT2FIX(PGRES_TUPLES_OK));
406
+ /* #result_status constant: Copy Out (from server) data transfer started. */
407
+ rb_define_const(rb_mPGconstants, "PGRES_COPY_OUT", INT2FIX(PGRES_COPY_OUT));
408
+ /* #result_status constant: Copy In (to server) data transfer started. */
409
+ rb_define_const(rb_mPGconstants, "PGRES_COPY_IN", INT2FIX(PGRES_COPY_IN));
410
+ /* #result_status constant: The server’s response was not understood. */
411
+ rb_define_const(rb_mPGconstants, "PGRES_BAD_RESPONSE", INT2FIX(PGRES_BAD_RESPONSE));
412
+ /* #result_status constant: A nonfatal error (a notice or warning) occurred. */
413
+ rb_define_const(rb_mPGconstants, "PGRES_NONFATAL_ERROR",INT2FIX(PGRES_NONFATAL_ERROR));
414
+ /* #result_status constant: A fatal error occurred. */
415
+ rb_define_const(rb_mPGconstants, "PGRES_FATAL_ERROR", INT2FIX(PGRES_FATAL_ERROR));
416
+ /* #result_status constant: Copy In/Out data transfer in progress. */
417
+ #ifdef HAVE_CONST_PGRES_COPY_BOTH
418
+ rb_define_const(rb_mPGconstants, "PGRES_COPY_BOTH", INT2FIX(PGRES_COPY_BOTH));
419
+ #endif
420
+ /* #result_status constant: Single tuple from larger resultset. */
421
+ #ifdef HAVE_CONST_PGRES_SINGLE_TUPLE
422
+ rb_define_const(rb_mPGconstants, "PGRES_SINGLE_TUPLE", INT2FIX(PGRES_SINGLE_TUPLE));
423
+ #endif
424
+
425
+ /****** Result CONSTANTS: result error field codes ******/
426
+
427
+ /* #result_error_field argument constant: The severity; the field contents
428
+ * are ERROR, FATAL, or PANIC (in an error message), or WARNING, NOTICE,
429
+ * DEBUG, INFO, or LOG (in a notice message), or a localized translation
430
+ * of one of these. Always present.
431
+ */
432
+ rb_define_const(rb_mPGconstants, "PG_DIAG_SEVERITY", INT2FIX(PG_DIAG_SEVERITY));
433
+
434
+ /* #result_error_field argument constant: The SQLSTATE code for the
435
+ * error. The SQLSTATE code identies the type of error that has occurred;
436
+ * it can be used by front-end applications to perform specic operations
437
+ * (such as er- ror handling) in response to a particular database
438
+ * error. For a list of the possible SQLSTATE codes, see Appendix A.
439
+ * This eld is not localizable, and is always present.
440
+ */
441
+ rb_define_const(rb_mPGconstants, "PG_DIAG_SQLSTATE", INT2FIX(PG_DIAG_SQLSTATE));
442
+
443
+ /* #result_error_field argument constant: The primary human-readable
444
+ * error message (typically one line). Always present. */
445
+ rb_define_const(rb_mPGconstants, "PG_DIAG_MESSAGE_PRIMARY", INT2FIX(PG_DIAG_MESSAGE_PRIMARY));
446
+
447
+ /* #result_error_field argument constant: Detail: an optional secondary
448
+ * error message carrying more detail about the problem. Might run to
449
+ * multiple lines.
450
+ */
451
+ rb_define_const(rb_mPGconstants, "PG_DIAG_MESSAGE_DETAIL", INT2FIX(PG_DIAG_MESSAGE_DETAIL));
452
+
453
+ /* #result_error_field argument constant: Hint: an optional suggestion
454
+ * what to do about the problem. This is intended to differ from detail
455
+ * in that it offers advice (potentially inappropriate) rather than
456
+ * hard facts. Might run to multiple lines.
457
+ */
458
+
459
+ rb_define_const(rb_mPGconstants, "PG_DIAG_MESSAGE_HINT", INT2FIX(PG_DIAG_MESSAGE_HINT));
460
+ /* #result_error_field argument constant: A string containing a decimal
461
+ * integer indicating an error cursor position as an index into the
462
+ * original statement string. The rst character has index 1, and
463
+ * positions are measured in characters not bytes.
464
+ */
465
+
466
+ rb_define_const(rb_mPGconstants, "PG_DIAG_STATEMENT_POSITION", INT2FIX(PG_DIAG_STATEMENT_POSITION));
467
+ /* #result_error_field argument constant: This is dened the same as
468
+ * the PG_DIAG_STATEMENT_POSITION eld, but it is used when the cursor
469
+ * position refers to an internally generated command rather than the
470
+ * one submitted by the client. The PG_DIAG_INTERNAL_QUERY eld will
471
+ * always appear when this eld appears.
472
+ */
473
+
474
+ rb_define_const(rb_mPGconstants, "PG_DIAG_INTERNAL_POSITION", INT2FIX(PG_DIAG_INTERNAL_POSITION));
475
+ /* #result_error_field argument constant: The text of a failed
476
+ * internally-generated command. This could be, for example, a SQL
477
+ * query issued by a PL/pgSQL function.
478
+ */
479
+
480
+ rb_define_const(rb_mPGconstants, "PG_DIAG_INTERNAL_QUERY", INT2FIX(PG_DIAG_INTERNAL_QUERY));
481
+ /* #result_error_field argument constant: An indication of the context
482
+ * in which the error occurred. Presently this includes a call stack
483
+ * traceback of active procedural language functions and internally-generated
484
+ * queries. The trace is one entry per line, most recent rst.
485
+ */
486
+
487
+ rb_define_const(rb_mPGconstants, "PG_DIAG_CONTEXT", INT2FIX(PG_DIAG_CONTEXT));
488
+ /* #result_error_field argument constant: The le name of the source-code
489
+ * location where the error was reported. */
490
+ rb_define_const(rb_mPGconstants, "PG_DIAG_SOURCE_FILE", INT2FIX(PG_DIAG_SOURCE_FILE));
491
+
492
+ /* #result_error_field argument constant: The line number of the
493
+ * source-code location where the error was reported. */
494
+ rb_define_const(rb_mPGconstants, "PG_DIAG_SOURCE_LINE", INT2FIX(PG_DIAG_SOURCE_LINE));
495
+
496
+ /* #result_error_field argument constant: The name of the source-code
497
+ * function reporting the error. */
498
+ rb_define_const(rb_mPGconstants, "PG_DIAG_SOURCE_FUNCTION", INT2FIX(PG_DIAG_SOURCE_FUNCTION));
499
+
500
+ #ifdef HAVE_CONST_PG_DIAG_TABLE_NAME
501
+ /* #result_error_field argument constant: If the error was associated with a
502
+ * specific database object, the name of the schema containing that object, if any. */
503
+ rb_define_const(rb_mPGconstants, "PG_DIAG_SCHEMA_NAME", INT2FIX(PG_DIAG_SCHEMA_NAME));
504
+
505
+ /* #result_error_field argument constant: If the error was associated with a
506
+ *specific table, the name of the table. (When this field is present, the schema name
507
+ * field provides the name of the table's schema.) */
508
+ rb_define_const(rb_mPGconstants, "PG_DIAG_TABLE_NAME", INT2FIX(PG_DIAG_TABLE_NAME));
509
+
510
+ /* #result_error_field argument constant: If the error was associated with a
511
+ * specific table column, the name of the column. (When this field is present, the
512
+ * schema and table name fields identify the table.) */
513
+ rb_define_const(rb_mPGconstants, "PG_DIAG_COLUMN_NAME", INT2FIX(PG_DIAG_COLUMN_NAME));
514
+
515
+ /* #result_error_field argument constant: If the error was associated with a
516
+ * specific datatype, the name of the datatype. (When this field is present, the
517
+ * schema name field provides the name of the datatype's schema.) */
518
+ rb_define_const(rb_mPGconstants, "PG_DIAG_DATATYPE_NAME", INT2FIX(PG_DIAG_DATATYPE_NAME));
519
+
520
+ /* #result_error_field argument constant: If the error was associated with a
521
+ * specific constraint, the name of the constraint. The table or domain that the
522
+ * constraint belongs to is reported using the fields listed above. (For this
523
+ * purpose, indexes are treated as constraints, even if they weren't created with
524
+ * constraint syntax.) */
525
+ rb_define_const(rb_mPGconstants, "PG_DIAG_CONSTRAINT_NAME", INT2FIX(PG_DIAG_CONSTRAINT_NAME));
526
+ #endif
527
+
528
+ /* Invalid OID constant */
529
+ rb_define_const(rb_mPGconstants, "INVALID_OID", INT2FIX(InvalidOid));
530
+ rb_define_const(rb_mPGconstants, "InvalidOid", INT2FIX(InvalidOid));
531
+
532
+ /* Add the constants to the toplevel namespace */
533
+ rb_include_module( rb_mPG, rb_mPGconstants );
534
+
535
+ #ifdef M17N_SUPPORTED
536
+ enc_pg2ruby = st_init_numtable();
537
+ s_id_index = rb_intern("@encoding");
538
+ #endif
539
+
540
+ /* Initialize the main extension classes */
541
+ init_pg_connection();
542
+ init_pg_result();
543
+ init_pg_errors();
544
+ }
545
+