pg 1.1.4 → 1.5.3

Sign up to get free protection for your applications and to get access to all the features.
Files changed (140) hide show
  1. checksums.yaml +4 -4
  2. checksums.yaml.gz.sig +0 -0
  3. data/.appveyor.yml +42 -0
  4. data/.gems +6 -0
  5. data/.github/workflows/binary-gems.yml +117 -0
  6. data/.github/workflows/source-gem.yml +137 -0
  7. data/.gitignore +22 -0
  8. data/.hgsigs +34 -0
  9. data/.hgtags +41 -0
  10. data/.irbrc +23 -0
  11. data/.pryrc +23 -0
  12. data/.tm_properties +21 -0
  13. data/.travis.yml +49 -0
  14. data/Gemfile +14 -0
  15. data/History.md +876 -0
  16. data/Manifest.txt +3 -3
  17. data/README-Windows.rdoc +4 -4
  18. data/README.ja.md +276 -0
  19. data/README.md +286 -0
  20. data/Rakefile +37 -137
  21. data/Rakefile.cross +62 -62
  22. data/certs/ged.pem +24 -0
  23. data/certs/larskanis-2022.pem +26 -0
  24. data/certs/larskanis-2023.pem +24 -0
  25. data/ext/errorcodes.def +76 -0
  26. data/ext/errorcodes.rb +0 -0
  27. data/ext/errorcodes.txt +21 -2
  28. data/ext/extconf.rb +101 -26
  29. data/ext/gvl_wrappers.c +4 -0
  30. data/ext/gvl_wrappers.h +23 -0
  31. data/ext/pg.c +203 -151
  32. data/ext/pg.h +48 -21
  33. data/ext/pg_binary_decoder.c +89 -10
  34. data/ext/pg_binary_encoder.c +238 -13
  35. data/ext/pg_coder.c +109 -34
  36. data/ext/pg_connection.c +1365 -976
  37. data/ext/pg_copy_coder.c +356 -35
  38. data/ext/pg_errors.c +1 -1
  39. data/ext/pg_record_coder.c +522 -0
  40. data/ext/pg_result.c +436 -171
  41. data/ext/pg_text_decoder.c +42 -18
  42. data/ext/pg_text_encoder.c +201 -56
  43. data/ext/pg_tuple.c +97 -66
  44. data/ext/pg_type_map.c +45 -11
  45. data/ext/pg_type_map_all_strings.c +21 -7
  46. data/ext/pg_type_map_by_class.c +59 -27
  47. data/ext/pg_type_map_by_column.c +80 -37
  48. data/ext/pg_type_map_by_mri_type.c +49 -20
  49. data/ext/pg_type_map_by_oid.c +62 -29
  50. data/ext/pg_type_map_in_ruby.c +56 -22
  51. data/ext/{util.c → pg_util.c} +7 -7
  52. data/lib/pg/basic_type_map_based_on_result.rb +67 -0
  53. data/lib/pg/basic_type_map_for_queries.rb +198 -0
  54. data/lib/pg/basic_type_map_for_results.rb +104 -0
  55. data/lib/pg/basic_type_registry.rb +299 -0
  56. data/lib/pg/binary_decoder/date.rb +9 -0
  57. data/lib/pg/binary_decoder/timestamp.rb +26 -0
  58. data/lib/pg/binary_encoder/timestamp.rb +20 -0
  59. data/lib/pg/coder.rb +35 -12
  60. data/lib/pg/connection.rb +744 -84
  61. data/lib/pg/exceptions.rb +15 -1
  62. data/lib/pg/result.rb +13 -1
  63. data/lib/pg/text_decoder/date.rb +18 -0
  64. data/lib/pg/text_decoder/inet.rb +9 -0
  65. data/lib/pg/text_decoder/json.rb +14 -0
  66. data/lib/pg/text_decoder/numeric.rb +9 -0
  67. data/lib/pg/text_decoder/timestamp.rb +30 -0
  68. data/lib/pg/text_encoder/date.rb +12 -0
  69. data/lib/pg/text_encoder/inet.rb +28 -0
  70. data/lib/pg/text_encoder/json.rb +14 -0
  71. data/lib/pg/text_encoder/numeric.rb +9 -0
  72. data/lib/pg/text_encoder/timestamp.rb +24 -0
  73. data/lib/pg/type_map_by_column.rb +2 -1
  74. data/lib/pg/version.rb +4 -0
  75. data/lib/pg.rb +94 -39
  76. data/misc/openssl-pg-segfault.rb +31 -0
  77. data/misc/postgres/History.txt +9 -0
  78. data/misc/postgres/Manifest.txt +5 -0
  79. data/misc/postgres/README.txt +21 -0
  80. data/misc/postgres/Rakefile +21 -0
  81. data/misc/postgres/lib/postgres.rb +16 -0
  82. data/misc/ruby-pg/History.txt +9 -0
  83. data/misc/ruby-pg/Manifest.txt +5 -0
  84. data/misc/ruby-pg/README.txt +21 -0
  85. data/misc/ruby-pg/Rakefile +21 -0
  86. data/misc/ruby-pg/lib/ruby/pg.rb +16 -0
  87. data/pg.gemspec +34 -0
  88. data/rakelib/task_extension.rb +46 -0
  89. data/sample/array_insert.rb +20 -0
  90. data/sample/async_api.rb +102 -0
  91. data/sample/async_copyto.rb +39 -0
  92. data/sample/async_mixed.rb +56 -0
  93. data/sample/check_conn.rb +21 -0
  94. data/sample/copydata.rb +71 -0
  95. data/sample/copyfrom.rb +81 -0
  96. data/sample/copyto.rb +19 -0
  97. data/sample/cursor.rb +21 -0
  98. data/sample/disk_usage_report.rb +177 -0
  99. data/sample/issue-119.rb +94 -0
  100. data/sample/losample.rb +69 -0
  101. data/sample/minimal-testcase.rb +17 -0
  102. data/sample/notify_wait.rb +72 -0
  103. data/sample/pg_statistics.rb +285 -0
  104. data/sample/replication_monitor.rb +222 -0
  105. data/sample/test_binary_values.rb +33 -0
  106. data/sample/wal_shipper.rb +434 -0
  107. data/sample/warehouse_partitions.rb +311 -0
  108. data/translation/.po4a-version +7 -0
  109. data/translation/po/all.pot +910 -0
  110. data/translation/po/ja.po +1047 -0
  111. data/translation/po4a.cfg +12 -0
  112. data.tar.gz.sig +0 -0
  113. metadata +151 -218
  114. metadata.gz.sig +0 -0
  115. data/ChangeLog +0 -6595
  116. data/History.rdoc +0 -492
  117. data/README.ja.rdoc +0 -14
  118. data/README.rdoc +0 -178
  119. data/lib/pg/basic_type_mapping.rb +0 -459
  120. data/lib/pg/binary_decoder.rb +0 -22
  121. data/lib/pg/constants.rb +0 -11
  122. data/lib/pg/text_decoder.rb +0 -47
  123. data/lib/pg/text_encoder.rb +0 -69
  124. data/spec/data/expected_trace.out +0 -26
  125. data/spec/data/random_binary_data +0 -0
  126. data/spec/helpers.rb +0 -380
  127. data/spec/pg/basic_type_mapping_spec.rb +0 -508
  128. data/spec/pg/connection_spec.rb +0 -1872
  129. data/spec/pg/connection_sync_spec.rb +0 -41
  130. data/spec/pg/result_spec.rb +0 -491
  131. data/spec/pg/tuple_spec.rb +0 -280
  132. data/spec/pg/type_map_by_class_spec.rb +0 -138
  133. data/spec/pg/type_map_by_column_spec.rb +0 -222
  134. data/spec/pg/type_map_by_mri_type_spec.rb +0 -136
  135. data/spec/pg/type_map_by_oid_spec.rb +0 -149
  136. data/spec/pg/type_map_in_ruby_spec.rb +0 -164
  137. data/spec/pg/type_map_spec.rb +0 -22
  138. data/spec/pg/type_spec.rb +0 -949
  139. data/spec/pg_spec.rb +0 -50
  140. /data/ext/{util.h → pg_util.h} +0 -0
@@ -1,459 +0,0 @@
1
- # -*- ruby -*-
2
-
3
- require 'pg' unless defined?( PG )
4
-
5
- # This module defines the mapping between OID and encoder/decoder classes for PG::BasicTypeMapForResults, PG::BasicTypeMapForQueries and PG::BasicTypeMapBasedOnResult.
6
- #
7
- # Additional types can be added like so:
8
- #
9
- # require 'pg'
10
- # require 'ipaddr'
11
- #
12
- # class InetDecoder < PG::SimpleDecoder
13
- # def decode(string, tuple=nil, field=nil)
14
- # IPAddr.new(string)
15
- # end
16
- # end
17
- # class InetEncoder < PG::SimpleEncoder
18
- # def encode(ip_addr)
19
- # ip_addr.to_s
20
- # end
21
- # end
22
- #
23
- # # 0 if for text format, can also be 1 for binary
24
- # PG::BasicTypeRegistry.register_type(0, 'inet', InetEncoder, InetDecoder)
25
- module PG::BasicTypeRegistry
26
- # An instance of this class stores the coders that should be used for a given wire format (text or binary)
27
- # and type cast direction (encoder or decoder).
28
- class CoderMap
29
- # Hash of text types that don't require quotation, when used within composite types.
30
- # type.name => true
31
- DONT_QUOTE_TYPES = %w[
32
- int2 int4 int8
33
- float4 float8
34
- oid
35
- bool
36
- date timestamp timestamptz
37
- ].inject({}){|h,e| h[e] = true; h }
38
-
39
- def initialize(result, coders_by_name, format, arraycoder)
40
- coder_map = {}
41
-
42
- _ranges, nodes = result.partition { |row| row['typinput'] == 'range_in' }
43
- leaves, nodes = nodes.partition { |row| row['typelem'].to_i == 0 }
44
- arrays, nodes = nodes.partition { |row| row['typinput'] == 'array_in' }
45
-
46
- # populate the enum types
47
- _enums, leaves = leaves.partition { |row| row['typinput'] == 'enum_in' }
48
- # enums.each do |row|
49
- # coder_map[row['oid'].to_i] = OID::Enum.new
50
- # end
51
-
52
- # populate the base types
53
- leaves.find_all { |row| coders_by_name.key?(row['typname']) }.each do |row|
54
- coder = coders_by_name[row['typname']].dup
55
- coder.oid = row['oid'].to_i
56
- coder.name = row['typname']
57
- coder.format = format
58
- coder_map[coder.oid] = coder
59
- end
60
-
61
- _records_by_oid = result.group_by { |row| row['oid'] }
62
-
63
- # populate composite types
64
- # nodes.each do |row|
65
- # add_oid row, records_by_oid, coder_map
66
- # end
67
-
68
- if arraycoder
69
- # populate array types
70
- arrays.each do |row|
71
- elements_coder = coder_map[row['typelem'].to_i]
72
- next unless elements_coder
73
-
74
- coder = arraycoder.new
75
- coder.oid = row['oid'].to_i
76
- coder.name = row['typname']
77
- coder.format = format
78
- coder.elements_type = elements_coder
79
- coder.needs_quotation = !DONT_QUOTE_TYPES[elements_coder.name]
80
- coder_map[coder.oid] = coder
81
- end
82
- end
83
-
84
- # populate range types
85
- # ranges.find_all { |row| coder_map.key? row['rngsubtype'].to_i }.each do |row|
86
- # subcoder = coder_map[row['rngsubtype'].to_i]
87
- # range = OID::Range.new subcoder
88
- # coder_map[row['oid'].to_i] = range
89
- # end
90
-
91
- @coders = coder_map.values
92
- @coders_by_name = @coders.inject({}){|h, t| h[t.name] = t; h }
93
- @coders_by_oid = @coders.inject({}){|h, t| h[t.oid] = t; h }
94
- @typenames_by_oid = result.inject({}){|h, t| h[t['oid'].to_i] = t['typname']; h }
95
- end
96
-
97
- attr_reader :coders
98
- attr_reader :coders_by_oid
99
- attr_reader :coders_by_name
100
- attr_reader :typenames_by_oid
101
-
102
- def coder_by_name(name)
103
- @coders_by_name[name]
104
- end
105
-
106
- def coder_by_oid(oid)
107
- @coders_by_oid[oid]
108
- end
109
- end
110
-
111
- private
112
-
113
- def supports_ranges?(connection)
114
- connection.server_version >= 90200
115
- end
116
-
117
- def build_coder_maps(connection)
118
- if supports_ranges?(connection)
119
- result = connection.exec <<-SQL
120
- SELECT t.oid, t.typname, t.typelem, t.typdelim, t.typinput, r.rngsubtype
121
- FROM pg_type as t
122
- LEFT JOIN pg_range as r ON oid = rngtypid
123
- SQL
124
- else
125
- result = connection.exec <<-SQL
126
- SELECT t.oid, t.typname, t.typelem, t.typdelim, t.typinput
127
- FROM pg_type as t
128
- SQL
129
- end
130
-
131
- [
132
- [0, :encoder, PG::TextEncoder::Array],
133
- [0, :decoder, PG::TextDecoder::Array],
134
- [1, :encoder, nil],
135
- [1, :decoder, nil],
136
- ].inject([]) do |h, (format, direction, arraycoder)|
137
- h[format] ||= {}
138
- h[format][direction] = CoderMap.new result, CODERS_BY_NAME[format][direction], format, arraycoder
139
- h
140
- end
141
- end
142
-
143
- ValidFormats = { 0 => true, 1 => true }
144
- ValidDirections = { :encoder => true, :decoder => true }
145
-
146
- def check_format_and_direction(format, direction)
147
- raise(ArgumentError, "Invalid format value %p" % format) unless ValidFormats[format]
148
- raise(ArgumentError, "Invalid direction %p" % direction) unless ValidDirections[direction]
149
- end
150
- protected :check_format_and_direction
151
-
152
- # The key of this hash maps to the `typname` column from the table.
153
- # encoder_map is then dynamically built with oids as the key and Type
154
- # objects as values.
155
- CODERS_BY_NAME = []
156
-
157
- # Register an OID type named +name+ with a typecasting encoder and decoder object in
158
- # +type+. +name+ should correspond to the `typname` column in
159
- # the `pg_type` table.
160
- # +format+ can be 0 for text format and 1 for binary.
161
- def self.register_type(format, name, encoder_class, decoder_class)
162
- CODERS_BY_NAME[format] ||= { encoder: {}, decoder: {} }
163
- CODERS_BY_NAME[format][:encoder][name] = encoder_class.new(name: name, format: format) if encoder_class
164
- CODERS_BY_NAME[format][:decoder][name] = decoder_class.new(name: name, format: format) if decoder_class
165
- end
166
-
167
- # Alias the +old+ type to the +new+ type.
168
- def self.alias_type(format, new, old)
169
- [:encoder, :decoder].each do |ende|
170
- enc = CODERS_BY_NAME[format][ende][old]
171
- if enc
172
- CODERS_BY_NAME[format][ende][new] = enc
173
- else
174
- CODERS_BY_NAME[format][ende].delete(new)
175
- end
176
- end
177
- end
178
-
179
- register_type 0, 'int2', PG::TextEncoder::Integer, PG::TextDecoder::Integer
180
- alias_type 0, 'int4', 'int2'
181
- alias_type 0, 'int8', 'int2'
182
- alias_type 0, 'oid', 'int2'
183
-
184
- register_type 0, 'numeric', PG::TextEncoder::Numeric, PG::TextDecoder::Numeric
185
- register_type 0, 'text', PG::TextEncoder::String, PG::TextDecoder::String
186
- alias_type 0, 'varchar', 'text'
187
- alias_type 0, 'char', 'text'
188
- alias_type 0, 'bpchar', 'text'
189
- alias_type 0, 'xml', 'text'
190
-
191
- # FIXME: why are we keeping these types as strings?
192
- # alias_type 'tsvector', 'text'
193
- # alias_type 'interval', 'text'
194
- # alias_type 'macaddr', 'text'
195
- # alias_type 'uuid', 'text'
196
- #
197
- # register_type 'money', OID::Money.new
198
- # There is no PG::TextEncoder::Bytea, because it's simple and more efficient to send bytea-data
199
- # in binary format, either with PG::BinaryEncoder::Bytea or in Hash param format.
200
- register_type 0, 'bytea', nil, PG::TextDecoder::Bytea
201
- register_type 0, 'bool', PG::TextEncoder::Boolean, PG::TextDecoder::Boolean
202
- # register_type 'bit', OID::Bit.new
203
- # register_type 'varbit', OID::Bit.new
204
-
205
- register_type 0, 'float4', PG::TextEncoder::Float, PG::TextDecoder::Float
206
- alias_type 0, 'float8', 'float4'
207
-
208
- register_type 0, 'timestamp', PG::TextEncoder::TimestampWithoutTimeZone, PG::TextDecoder::TimestampWithoutTimeZone
209
- register_type 0, 'timestamptz', PG::TextEncoder::TimestampWithTimeZone, PG::TextDecoder::TimestampWithTimeZone
210
- register_type 0, 'date', PG::TextEncoder::Date, PG::TextDecoder::Date
211
- # register_type 'time', OID::Time.new
212
- #
213
- # register_type 'path', OID::Text.new
214
- # register_type 'point', OID::Point.new
215
- # register_type 'polygon', OID::Text.new
216
- # register_type 'circle', OID::Text.new
217
- # register_type 'hstore', OID::Hstore.new
218
- register_type 0, 'json', PG::TextEncoder::JSON, PG::TextDecoder::JSON
219
- alias_type 0, 'jsonb', 'json'
220
- # register_type 'citext', OID::Text.new
221
- # register_type 'ltree', OID::Text.new
222
- #
223
- register_type 0, 'inet', PG::TextEncoder::Inet, PG::TextDecoder::Inet
224
- alias_type 0, 'cidr', 'inet'
225
-
226
-
227
-
228
- register_type 1, 'int2', PG::BinaryEncoder::Int2, PG::BinaryDecoder::Integer
229
- register_type 1, 'int4', PG::BinaryEncoder::Int4, PG::BinaryDecoder::Integer
230
- register_type 1, 'int8', PG::BinaryEncoder::Int8, PG::BinaryDecoder::Integer
231
- alias_type 1, 'oid', 'int2'
232
-
233
- register_type 1, 'text', PG::BinaryEncoder::String, PG::BinaryDecoder::String
234
- alias_type 1, 'varchar', 'text'
235
- alias_type 1, 'char', 'text'
236
- alias_type 1, 'bpchar', 'text'
237
- alias_type 1, 'xml', 'text'
238
-
239
- register_type 1, 'bytea', PG::BinaryEncoder::Bytea, PG::BinaryDecoder::Bytea
240
- register_type 1, 'bool', PG::BinaryEncoder::Boolean, PG::BinaryDecoder::Boolean
241
- register_type 1, 'float4', nil, PG::BinaryDecoder::Float
242
- register_type 1, 'float8', nil, PG::BinaryDecoder::Float
243
- register_type 1, 'timestamp', nil, PG::BinaryDecoder::TimestampUtc
244
- register_type 1, 'timestamptz', nil, PG::BinaryDecoder::TimestampUtcToLocal
245
- end
246
-
247
- # Simple set of rules for type casting common PostgreSQL types to Ruby.
248
- #
249
- # OIDs of supported type casts are not hard-coded in the sources, but are retrieved from the
250
- # PostgreSQL's pg_type table in PG::BasicTypeMapForResults.new .
251
- #
252
- # Result values are type casted based on the type OID of the given result column.
253
- #
254
- # Higher level libraries will most likely not make use of this class, but use their
255
- # own set of rules to choose suitable encoders and decoders.
256
- #
257
- # Example:
258
- # conn = PG::Connection.new
259
- # # Assign a default ruleset for type casts of output values.
260
- # conn.type_map_for_results = PG::BasicTypeMapForResults.new(conn)
261
- # # Execute a query.
262
- # res = conn.exec_params( "SELECT $1::INT", ['5'] )
263
- # # Retrieve and cast the result value. Value format is 0 (text) and OID is 20. Therefore typecasting
264
- # # is done by PG::TextDecoder::Integer internally for all value retrieval methods.
265
- # res.values # => [[5]]
266
- #
267
- # PG::TypeMapByOid#fit_to_result(result, false) can be used to generate
268
- # a result independent PG::TypeMapByColumn type map, which can subsequently be used
269
- # to cast #get_copy_data fields:
270
- #
271
- # For the following table:
272
- # conn.exec( "CREATE TABLE copytable AS VALUES('a', 123, '{5,4,3}'::INT[])" )
273
- #
274
- # # Retrieve table OIDs per empty result set.
275
- # res = conn.exec( "SELECT * FROM copytable LIMIT 0" )
276
- # # Build a type map for common database to ruby type decoders.
277
- # btm = PG::BasicTypeMapForResults.new(conn)
278
- # # Build a PG::TypeMapByColumn with decoders suitable for copytable.
279
- # tm = btm.build_column_map( res )
280
- # row_decoder = PG::TextDecoder::CopyRow.new type_map: tm
281
- #
282
- # conn.copy_data( "COPY copytable TO STDOUT", row_decoder ) do |res|
283
- # while row=conn.get_copy_data
284
- # p row
285
- # end
286
- # end
287
- # This prints the rows with type casted columns:
288
- # ["a", 123, [5, 4, 3]]
289
- #
290
- # See also PG::BasicTypeMapBasedOnResult for the encoder direction and PG::BasicTypeRegistry for the definition of additional types.
291
- class PG::BasicTypeMapForResults < PG::TypeMapByOid
292
- include PG::BasicTypeRegistry
293
-
294
- class WarningTypeMap < PG::TypeMapInRuby
295
- def initialize(typenames)
296
- @already_warned = Hash.new{|h, k| h[k] = {} }
297
- @typenames_by_oid = typenames
298
- end
299
-
300
- def typecast_result_value(result, _tuple, field)
301
- format = result.fformat(field)
302
- oid = result.ftype(field)
303
- unless @already_warned[format][oid]
304
- STDERR.puts "Warning: no type cast defined for type #{@typenames_by_oid[format][oid].inspect} with oid #{oid}. Please cast this type explicitly to TEXT to be safe for future changes."
305
- @already_warned[format][oid] = true
306
- end
307
- super
308
- end
309
- end
310
-
311
- def initialize(connection)
312
- @coder_maps = build_coder_maps(connection)
313
-
314
- # Populate TypeMapByOid hash with decoders
315
- @coder_maps.map{|f| f[:decoder].coders }.flatten.each do |coder|
316
- add_coder(coder)
317
- end
318
-
319
- typenames = @coder_maps.map{|f| f[:decoder].typenames_by_oid }
320
- self.default_type_map = WarningTypeMap.new(typenames)
321
- end
322
- end
323
-
324
- # Simple set of rules for type casting common PostgreSQL types from Ruby
325
- # to PostgreSQL.
326
- #
327
- # OIDs of supported type casts are not hard-coded in the sources, but are retrieved from the
328
- # PostgreSQL's pg_type table in PG::BasicTypeMapBasedOnResult.new .
329
- #
330
- # This class works equal to PG::BasicTypeMapForResults, but does not define decoders for
331
- # the given result OIDs, but encoders. So it can be used to type cast field values based on
332
- # the type OID retrieved by a separate SQL query.
333
- #
334
- # PG::TypeMapByOid#build_column_map(result) can be used to generate a result independent
335
- # PG::TypeMapByColumn type map, which can subsequently be used to cast query bind parameters
336
- # or #put_copy_data fields.
337
- #
338
- # Example:
339
- # conn.exec( "CREATE TEMP TABLE copytable (t TEXT, i INT, ai INT[])" )
340
- #
341
- # # Retrieve table OIDs per empty result set.
342
- # res = conn.exec( "SELECT * FROM copytable LIMIT 0" )
343
- # # Build a type map for common ruby to database type encoders.
344
- # btm = PG::BasicTypeMapBasedOnResult.new(conn)
345
- # # Build a PG::TypeMapByColumn with encoders suitable for copytable.
346
- # tm = btm.build_column_map( res )
347
- # row_encoder = PG::TextEncoder::CopyRow.new type_map: tm
348
- #
349
- # conn.copy_data( "COPY copytable FROM STDIN", row_encoder ) do |res|
350
- # conn.put_copy_data ['a', 123, [5,4,3]]
351
- # end
352
- # This inserts a single row into copytable with type casts from ruby to
353
- # database types.
354
- class PG::BasicTypeMapBasedOnResult < PG::TypeMapByOid
355
- include PG::BasicTypeRegistry
356
-
357
- def initialize(connection)
358
- @coder_maps = build_coder_maps(connection)
359
-
360
- # Populate TypeMapByOid hash with encoders
361
- @coder_maps.map{|f| f[:encoder].coders }.flatten.each do |coder|
362
- add_coder(coder)
363
- end
364
- end
365
- end
366
-
367
- # Simple set of rules for type casting common Ruby types to PostgreSQL.
368
- #
369
- # OIDs of supported type casts are not hard-coded in the sources, but are retrieved from the
370
- # PostgreSQL's pg_type table in PG::BasicTypeMapForQueries.new .
371
- #
372
- # Query params are type casted based on the class of the given value.
373
- #
374
- # Higher level libraries will most likely not make use of this class, but use their
375
- # own derivation of PG::TypeMapByClass or another set of rules to choose suitable
376
- # encoders and decoders for the values to be sent.
377
- #
378
- # Example:
379
- # conn = PG::Connection.new
380
- # # Assign a default ruleset for type casts of input and output values.
381
- # conn.type_map_for_queries = PG::BasicTypeMapForQueries.new(conn)
382
- # # Execute a query. The Integer param value is typecasted internally by PG::BinaryEncoder::Int8.
383
- # # The format of the parameter is set to 1 (binary) and the OID of this parameter is set to 20 (int8).
384
- # res = conn.exec_params( "SELECT $1", [5] )
385
- class PG::BasicTypeMapForQueries < PG::TypeMapByClass
386
- include PG::BasicTypeRegistry
387
-
388
- def initialize(connection)
389
- @coder_maps = build_coder_maps(connection)
390
-
391
- populate_encoder_list
392
- @array_encoders_by_klass = array_encoders_by_klass
393
- @anyarray_encoder = coder_by_name(0, :encoder, '_any')
394
- end
395
-
396
- private
397
-
398
- def coder_by_name(format, direction, name)
399
- check_format_and_direction(format, direction)
400
- @coder_maps[format][direction].coder_by_name(name)
401
- end
402
-
403
- def populate_encoder_list
404
- DEFAULT_TYPE_MAP.each do |klass, selector|
405
- if Array === selector
406
- format, name, oid_name = selector
407
- coder = coder_by_name(format, :encoder, name).dup
408
- if oid_name
409
- coder.oid = coder_by_name(format, :encoder, oid_name).oid
410
- else
411
- coder.oid = 0
412
- end
413
- self[klass] = coder
414
- else
415
- self[klass] = selector
416
- end
417
- end
418
- end
419
-
420
- def array_encoders_by_klass
421
- DEFAULT_ARRAY_TYPE_MAP.inject({}) do |h, (klass, (format, name))|
422
- h[klass] = coder_by_name(format, :encoder, name)
423
- h
424
- end
425
- end
426
-
427
- def get_array_type(value)
428
- elem = value
429
- while elem.kind_of?(Array)
430
- elem = elem.first
431
- end
432
- @array_encoders_by_klass[elem.class] ||
433
- elem.class.ancestors.lazy.map{|ancestor| @array_encoders_by_klass[ancestor] }.find{|a| a } ||
434
- @anyarray_encoder
435
- end
436
-
437
- DEFAULT_TYPE_MAP = {
438
- TrueClass => [1, 'bool', 'bool'],
439
- FalseClass => [1, 'bool', 'bool'],
440
- # We use text format and no type OID for numbers, because setting the OID can lead
441
- # to unnecessary type conversions on server side.
442
- Integer => [0, 'int8'],
443
- Float => [0, 'float8'],
444
- BigDecimal => [0, 'numeric'],
445
- # We use text format and no type OID for IPAddr, because setting the OID can lead
446
- # to unnecessary inet/cidr conversions on the server side.
447
- IPAddr => [0, 'inet'],
448
- Array => :get_array_type,
449
- }
450
-
451
- DEFAULT_ARRAY_TYPE_MAP = {
452
- TrueClass => [0, '_bool'],
453
- FalseClass => [0, '_bool'],
454
- Integer => [0, '_int8'],
455
- String => [0, '_text'],
456
- Float => [0, '_float8'],
457
- }
458
-
459
- end
@@ -1,22 +0,0 @@
1
- # -*- ruby -*-
2
-
3
- module PG
4
- module BinaryDecoder
5
- # Convenience classes for timezone options
6
- class TimestampUtc < Timestamp
7
- def initialize(params={})
8
- super(params.merge(flags: PG::Coder::TIMESTAMP_DB_UTC | PG::Coder::TIMESTAMP_APP_UTC))
9
- end
10
- end
11
- class TimestampUtcToLocal < Timestamp
12
- def initialize(params={})
13
- super(params.merge(flags: PG::Coder::TIMESTAMP_DB_UTC | PG::Coder::TIMESTAMP_APP_LOCAL))
14
- end
15
- end
16
- class TimestampLocal < Timestamp
17
- def initialize(params={})
18
- super(params.merge(flags: PG::Coder::TIMESTAMP_DB_LOCAL | PG::Coder::TIMESTAMP_APP_LOCAL))
19
- end
20
- end
21
- end
22
- end # module PG
data/lib/pg/constants.rb DELETED
@@ -1,11 +0,0 @@
1
- # -*- ruby -*-
2
-
3
- require 'pg' unless defined?( PG )
4
-
5
-
6
- module PG::Constants
7
-
8
- # Most of these are defined in the extension.
9
-
10
- end # module PG::Constants
11
-
@@ -1,47 +0,0 @@
1
- # -*- ruby -*-
2
-
3
- require 'date'
4
- require 'json'
5
-
6
- module PG
7
- module TextDecoder
8
- class Date < SimpleDecoder
9
- ISO_DATE = /\A(\d{4})-(\d\d)-(\d\d)\z/
10
-
11
- def decode(string, tuple=nil, field=nil)
12
- if string =~ ISO_DATE
13
- ::Date.new $1.to_i, $2.to_i, $3.to_i
14
- else
15
- string
16
- end
17
- end
18
- end
19
-
20
- class JSON < SimpleDecoder
21
- def decode(string, tuple=nil, field=nil)
22
- ::JSON.parse(string, quirks_mode: true)
23
- end
24
- end
25
-
26
- # Convenience classes for timezone options
27
- class TimestampUtc < Timestamp
28
- def initialize(params={})
29
- super(params.merge(flags: PG::Coder::TIMESTAMP_DB_UTC | PG::Coder::TIMESTAMP_APP_UTC))
30
- end
31
- end
32
- class TimestampUtcToLocal < Timestamp
33
- def initialize(params={})
34
- super(params.merge(flags: PG::Coder::TIMESTAMP_DB_UTC | PG::Coder::TIMESTAMP_APP_LOCAL))
35
- end
36
- end
37
- class TimestampLocal < Timestamp
38
- def initialize(params={})
39
- super(params.merge(flags: PG::Coder::TIMESTAMP_DB_LOCAL | PG::Coder::TIMESTAMP_APP_LOCAL))
40
- end
41
- end
42
-
43
- # For backward compatibility:
44
- TimestampWithoutTimeZone = TimestampLocal
45
- TimestampWithTimeZone = Timestamp
46
- end
47
- end # module PG
@@ -1,69 +0,0 @@
1
- # -*- ruby -*-
2
-
3
- require 'json'
4
- require 'ipaddr'
5
-
6
- module PG
7
- module TextEncoder
8
- class Date < SimpleEncoder
9
- STRFTIME_ISO_DATE = "%Y-%m-%d".freeze
10
- def encode(value)
11
- value.respond_to?(:strftime) ? value.strftime(STRFTIME_ISO_DATE) : value
12
- end
13
- end
14
-
15
- class TimestampWithoutTimeZone < SimpleEncoder
16
- STRFTIME_ISO_DATETIME_WITHOUT_TIMEZONE = "%Y-%m-%d %H:%M:%S.%N".freeze
17
- def encode(value)
18
- value.respond_to?(:strftime) ? value.strftime(STRFTIME_ISO_DATETIME_WITHOUT_TIMEZONE) : value
19
- end
20
- end
21
-
22
- class TimestampUtc < SimpleEncoder
23
- STRFTIME_ISO_DATETIME_WITHOUT_TIMEZONE_UTC = "%Y-%m-%d %H:%M:%S.%N".freeze
24
- def encode(value)
25
- value.respond_to?(:utc) ? value.utc.strftime(STRFTIME_ISO_DATETIME_WITHOUT_TIMEZONE_UTC) : value
26
- end
27
- end
28
-
29
- class TimestampWithTimeZone < SimpleEncoder
30
- STRFTIME_ISO_DATETIME_WITH_TIMEZONE = "%Y-%m-%d %H:%M:%S.%N %:z".freeze
31
- def encode(value)
32
- value.respond_to?(:strftime) ? value.strftime(STRFTIME_ISO_DATETIME_WITH_TIMEZONE) : value
33
- end
34
- end
35
-
36
- class Numeric < SimpleEncoder
37
- def encode(value)
38
- value.is_a?(BigDecimal) ? value.to_s('F') : value
39
- end
40
- end
41
-
42
- class JSON < SimpleEncoder
43
- def encode(value)
44
- ::JSON.generate(value, quirks_mode: true)
45
- end
46
- end
47
-
48
- class Inet < SimpleEncoder
49
- def encode(value)
50
- case value
51
- when IPAddr
52
- default_prefix = (value.family == Socket::AF_INET ? 32 : 128)
53
- s = value.to_s
54
- if value.respond_to?(:prefix)
55
- prefix = value.prefix
56
- else
57
- range = value.to_range
58
- prefix = default_prefix - Math.log(((range.end.to_i - range.begin.to_i) + 1), 2).to_i
59
- end
60
- s << "/" << prefix.to_s if prefix != default_prefix
61
- s
62
- else
63
- value
64
- end
65
- end
66
- end
67
- end
68
- end # module PG
69
-
@@ -1,26 +0,0 @@
1
- To backend> Msg Q
2
- To backend> "SELECT 1 AS one"
3
- To backend> Msg complete, length 21
4
- From backend> T
5
- From backend (#4)> 28
6
- From backend (#2)> 1
7
- From backend> "one"
8
- From backend (#4)> 0
9
- From backend (#2)> 0
10
- From backend (#4)> 23
11
- From backend (#2)> 4
12
- From backend (#4)> -1
13
- From backend (#2)> 0
14
- From backend> D
15
- From backend (#4)> 11
16
- From backend (#2)> 1
17
- From backend (#4)> 1
18
- From backend (1)> 1
19
- From backend> C
20
- From backend (#4)> 11
21
- From backend> "SELECT"
22
- From backend> Z
23
- From backend (#4)> 5
24
- From backend> Z
25
- From backend (#4)> 5
26
- From backend> T
Binary file