pg 1.3.0.rc2-x64-mingw-ucrt

Sign up to get free protection for your applications and to get access to all the features.
Files changed (111) hide show
  1. checksums.yaml +7 -0
  2. checksums.yaml.gz.sig +3 -0
  3. data/.appveyor.yml +36 -0
  4. data/.gems +6 -0
  5. data/.gemtest +0 -0
  6. data/.github/workflows/binary-gems.yml +85 -0
  7. data/.github/workflows/source-gem.yml +130 -0
  8. data/.gitignore +13 -0
  9. data/.hgsigs +34 -0
  10. data/.hgtags +41 -0
  11. data/.irbrc +23 -0
  12. data/.pryrc +23 -0
  13. data/.tm_properties +21 -0
  14. data/.travis.yml +49 -0
  15. data/BSDL +22 -0
  16. data/Contributors.rdoc +46 -0
  17. data/Gemfile +14 -0
  18. data/History.rdoc +648 -0
  19. data/LICENSE +56 -0
  20. data/Manifest.txt +72 -0
  21. data/POSTGRES +23 -0
  22. data/README-OS_X.rdoc +68 -0
  23. data/README-Windows.rdoc +56 -0
  24. data/README.ja.rdoc +13 -0
  25. data/README.rdoc +214 -0
  26. data/Rakefile +106 -0
  27. data/Rakefile.cross +300 -0
  28. data/certs/ged.pem +24 -0
  29. data/ext/errorcodes.def +1040 -0
  30. data/ext/errorcodes.rb +45 -0
  31. data/ext/errorcodes.txt +496 -0
  32. data/ext/extconf.rb +165 -0
  33. data/ext/gvl_wrappers.c +21 -0
  34. data/ext/gvl_wrappers.h +264 -0
  35. data/ext/pg.c +732 -0
  36. data/ext/pg.h +385 -0
  37. data/ext/pg_binary_decoder.c +229 -0
  38. data/ext/pg_binary_encoder.c +163 -0
  39. data/ext/pg_coder.c +615 -0
  40. data/ext/pg_connection.c +4415 -0
  41. data/ext/pg_copy_coder.c +628 -0
  42. data/ext/pg_errors.c +95 -0
  43. data/ext/pg_record_coder.c +519 -0
  44. data/ext/pg_result.c +1683 -0
  45. data/ext/pg_text_decoder.c +987 -0
  46. data/ext/pg_text_encoder.c +814 -0
  47. data/ext/pg_tuple.c +575 -0
  48. data/ext/pg_type_map.c +199 -0
  49. data/ext/pg_type_map_all_strings.c +129 -0
  50. data/ext/pg_type_map_by_class.c +269 -0
  51. data/ext/pg_type_map_by_column.c +349 -0
  52. data/ext/pg_type_map_by_mri_type.c +313 -0
  53. data/ext/pg_type_map_by_oid.c +385 -0
  54. data/ext/pg_type_map_in_ruby.c +330 -0
  55. data/ext/pg_util.c +149 -0
  56. data/ext/pg_util.h +65 -0
  57. data/ext/vc/pg.sln +26 -0
  58. data/ext/vc/pg_18/pg.vcproj +216 -0
  59. data/ext/vc/pg_19/pg_19.vcproj +209 -0
  60. data/lib/3.1/pg_ext.so +0 -0
  61. data/lib/pg/basic_type_map_based_on_result.rb +47 -0
  62. data/lib/pg/basic_type_map_for_queries.rb +193 -0
  63. data/lib/pg/basic_type_map_for_results.rb +81 -0
  64. data/lib/pg/basic_type_registry.rb +296 -0
  65. data/lib/pg/binary_decoder.rb +23 -0
  66. data/lib/pg/coder.rb +104 -0
  67. data/lib/pg/connection.rb +813 -0
  68. data/lib/pg/constants.rb +12 -0
  69. data/lib/pg/exceptions.rb +12 -0
  70. data/lib/pg/result.rb +43 -0
  71. data/lib/pg/text_decoder.rb +46 -0
  72. data/lib/pg/text_encoder.rb +59 -0
  73. data/lib/pg/tuple.rb +30 -0
  74. data/lib/pg/type_map_by_column.rb +16 -0
  75. data/lib/pg/version.rb +4 -0
  76. data/lib/pg.rb +87 -0
  77. data/lib/x64-mingw-ucrt/libpq.dll +0 -0
  78. data/misc/openssl-pg-segfault.rb +31 -0
  79. data/misc/postgres/History.txt +9 -0
  80. data/misc/postgres/Manifest.txt +5 -0
  81. data/misc/postgres/README.txt +21 -0
  82. data/misc/postgres/Rakefile +21 -0
  83. data/misc/postgres/lib/postgres.rb +16 -0
  84. data/misc/ruby-pg/History.txt +9 -0
  85. data/misc/ruby-pg/Manifest.txt +5 -0
  86. data/misc/ruby-pg/README.txt +21 -0
  87. data/misc/ruby-pg/Rakefile +21 -0
  88. data/misc/ruby-pg/lib/ruby/pg.rb +16 -0
  89. data/pg.gemspec +32 -0
  90. data/sample/array_insert.rb +20 -0
  91. data/sample/async_api.rb +106 -0
  92. data/sample/async_copyto.rb +39 -0
  93. data/sample/async_mixed.rb +56 -0
  94. data/sample/check_conn.rb +21 -0
  95. data/sample/copydata.rb +71 -0
  96. data/sample/copyfrom.rb +81 -0
  97. data/sample/copyto.rb +19 -0
  98. data/sample/cursor.rb +21 -0
  99. data/sample/disk_usage_report.rb +177 -0
  100. data/sample/issue-119.rb +94 -0
  101. data/sample/losample.rb +69 -0
  102. data/sample/minimal-testcase.rb +17 -0
  103. data/sample/notify_wait.rb +72 -0
  104. data/sample/pg_statistics.rb +285 -0
  105. data/sample/replication_monitor.rb +222 -0
  106. data/sample/test_binary_values.rb +33 -0
  107. data/sample/wal_shipper.rb +434 -0
  108. data/sample/warehouse_partitions.rb +311 -0
  109. data.tar.gz.sig +0 -0
  110. metadata +188 -0
  111. metadata.gz.sig +0 -0
@@ -0,0 +1,47 @@
1
+ # -*- ruby -*-
2
+ # frozen_string_literal: true
3
+
4
+ require 'pg' unless defined?( PG )
5
+
6
+ # Simple set of rules for type casting common PostgreSQL types from Ruby
7
+ # to PostgreSQL.
8
+ #
9
+ # OIDs of supported type casts are not hard-coded in the sources, but are retrieved from the
10
+ # PostgreSQL's +pg_type+ table in PG::BasicTypeMapBasedOnResult.new .
11
+ #
12
+ # This class works equal to PG::BasicTypeMapForResults, but does not define decoders for
13
+ # the given result OIDs, but encoders. So it can be used to type cast field values based on
14
+ # the type OID retrieved by a separate SQL query.
15
+ #
16
+ # PG::TypeMapByOid#build_column_map(result) can be used to generate a result independent
17
+ # PG::TypeMapByColumn type map, which can subsequently be used to cast query bind parameters
18
+ # or #put_copy_data fields.
19
+ #
20
+ # Example:
21
+ # conn.exec( "CREATE TEMP TABLE copytable (t TEXT, i INT, ai INT[])" )
22
+ #
23
+ # # Retrieve table OIDs per empty result set.
24
+ # res = conn.exec( "SELECT * FROM copytable LIMIT 0" )
25
+ # # Build a type map for common ruby to database type encoders.
26
+ # btm = PG::BasicTypeMapBasedOnResult.new(conn)
27
+ # # Build a PG::TypeMapByColumn with encoders suitable for copytable.
28
+ # tm = btm.build_column_map( res )
29
+ # row_encoder = PG::TextEncoder::CopyRow.new type_map: tm
30
+ #
31
+ # conn.copy_data( "COPY copytable FROM STDIN", row_encoder ) do |res|
32
+ # conn.put_copy_data ['a', 123, [5,4,3]]
33
+ # end
34
+ # This inserts a single row into copytable with type casts from ruby to
35
+ # database types.
36
+ class PG::BasicTypeMapBasedOnResult < PG::TypeMapByOid
37
+ include PG::BasicTypeRegistry::Checker
38
+
39
+ def initialize(connection_or_coder_maps, registry: nil)
40
+ @coder_maps = build_coder_maps(connection_or_coder_maps, registry: registry)
41
+
42
+ # Populate TypeMapByOid hash with encoders
43
+ @coder_maps.each_format(:encoder).flat_map{|f| f.coders }.each do |coder|
44
+ add_coder(coder)
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,193 @@
1
+ # -*- ruby -*-
2
+ # frozen_string_literal: true
3
+
4
+ require 'pg' unless defined?( PG )
5
+
6
+ # Simple set of rules for type casting common Ruby types to PostgreSQL.
7
+ #
8
+ # OIDs of supported type casts are not hard-coded in the sources, but are retrieved from the
9
+ # PostgreSQL's pg_type table in PG::BasicTypeMapForQueries.new .
10
+ #
11
+ # Query params are type casted based on the class of the given value.
12
+ #
13
+ # Higher level libraries will most likely not make use of this class, but use their
14
+ # own derivation of PG::TypeMapByClass or another set of rules to choose suitable
15
+ # encoders and decoders for the values to be sent.
16
+ #
17
+ # Example:
18
+ # conn = PG::Connection.new
19
+ # # Assign a default ruleset for type casts of input and output values.
20
+ # conn.type_map_for_queries = PG::BasicTypeMapForQueries.new(conn)
21
+ # # Execute a query. The Integer param value is typecasted internally by PG::BinaryEncoder::Int8.
22
+ # # The format of the parameter is set to 0 (text) and the OID of this parameter is set to 20 (int8).
23
+ # res = conn.exec_params( "SELECT $1", [5] )
24
+ class PG::BasicTypeMapForQueries < PG::TypeMapByClass
25
+ # Helper class for submission of binary strings into bytea columns.
26
+ #
27
+ # Since PG::BasicTypeMapForQueries chooses the encoder to be used by the class of the submitted value,
28
+ # it's necessary to send binary strings as BinaryData.
29
+ # That way they're distinct from text strings.
30
+ # Please note however that PG::BasicTypeMapForResults delivers bytea columns as plain String
31
+ # with binary encoding.
32
+ #
33
+ # conn.type_map_for_queries = PG::BasicTypeMapForQueries.new(conn)
34
+ # conn.exec("CREATE TEMP TABLE test (data bytea)")
35
+ # bd = PG::BasicTypeMapForQueries::BinaryData.new("ab\xff\0cd")
36
+ # conn.exec_params("INSERT INTO test (data) VALUES ($1)", [bd])
37
+ class BinaryData < String
38
+ end
39
+
40
+ class UndefinedEncoder < RuntimeError
41
+ end
42
+
43
+ include PG::BasicTypeRegistry::Checker
44
+
45
+ # Create a new type map for query submission
46
+ #
47
+ # Options:
48
+ # * +registry+: Custom type registry, nil for default global registry
49
+ # * +if_undefined+: Optional +Proc+ object which is called, if no type for an parameter class is not defined in the registry.
50
+ def initialize(connection_or_coder_maps, registry: nil, if_undefined: nil)
51
+ @coder_maps = build_coder_maps(connection_or_coder_maps, registry: registry)
52
+ @array_encoders_by_klass = array_encoders_by_klass
53
+ @encode_array_as = :array
54
+ @if_undefined = if_undefined || proc { |oid_name, format|
55
+ raise UndefinedEncoder, "no encoder defined for type #{oid_name.inspect} format #{format}"
56
+ }
57
+ init_encoders
58
+ end
59
+
60
+ # Change the mechanism that is used to encode ruby array values
61
+ #
62
+ # Possible values:
63
+ # * +:array+ : Encode the ruby array as a PostgreSQL array.
64
+ # The array element type is inferred from the class of the first array element. This is the default.
65
+ # * +:json+ : Encode the ruby array as a JSON document.
66
+ # * +:record+ : Encode the ruby array as a composite type row.
67
+ # * <code>"_type"</code> : Encode the ruby array as a particular PostgreSQL type.
68
+ # All PostgreSQL array types are supported.
69
+ # If there's an encoder registered for the elements +type+, it will be used.
70
+ # Otherwise a string conversion (by +value.to_s+) is done.
71
+ def encode_array_as=(pg_type)
72
+ case pg_type
73
+ when :array
74
+ when :json
75
+ when :record
76
+ when /\A_/
77
+ else
78
+ raise ArgumentError, "invalid pg_type #{pg_type.inspect}"
79
+ end
80
+
81
+ @encode_array_as = pg_type
82
+
83
+ init_encoders
84
+ end
85
+
86
+ attr_reader :encode_array_as
87
+
88
+ private
89
+
90
+ def init_encoders
91
+ coders.each { |kl, c| self[kl] = nil } # Clear type map
92
+ populate_encoder_list
93
+ @textarray_encoder = coder_by_name(0, :encoder, '_text')
94
+ end
95
+
96
+ def coder_by_name(format, direction, name)
97
+ check_format_and_direction(format, direction)
98
+ @coder_maps.map_for(format, direction).coder_by_name(name)
99
+ end
100
+
101
+ def undefined(name, format)
102
+ @if_undefined.call(name, format)
103
+ end
104
+
105
+ def populate_encoder_list
106
+ DEFAULT_TYPE_MAP.each do |klass, selector|
107
+ if Array === selector
108
+ format, name, oid_name = selector
109
+ coder = coder_by_name(format, :encoder, name).dup
110
+ if coder
111
+ if oid_name
112
+ oid_coder = coder_by_name(format, :encoder, oid_name)
113
+ if oid_coder
114
+ coder.oid = oid_coder.oid
115
+ else
116
+ undefined(oid_name, format)
117
+ end
118
+ else
119
+ coder.oid = 0
120
+ end
121
+ self[klass] = coder
122
+ else
123
+ undefined(name, format)
124
+ end
125
+ else
126
+
127
+ case @encode_array_as
128
+ when :array
129
+ self[klass] = selector
130
+ when :json
131
+ self[klass] = PG::TextEncoder::JSON.new
132
+ when :record
133
+ self[klass] = PG::TextEncoder::Record.new type_map: self
134
+ when /\A_/
135
+ coder = coder_by_name(0, :encoder, @encode_array_as)
136
+ if coder
137
+ self[klass] = coder
138
+ else
139
+ undefined(@encode_array_as, format)
140
+ end
141
+ else
142
+ raise ArgumentError, "invalid pg_type #{@encode_array_as.inspect}"
143
+ end
144
+ end
145
+ end
146
+ end
147
+
148
+ def array_encoders_by_klass
149
+ DEFAULT_ARRAY_TYPE_MAP.inject({}) do |h, (klass, (format, name))|
150
+ h[klass] = coder_by_name(format, :encoder, name)
151
+ h
152
+ end
153
+ end
154
+
155
+ def get_array_type(value)
156
+ elem = value
157
+ while elem.kind_of?(Array)
158
+ elem = elem.first
159
+ end
160
+ @array_encoders_by_klass[elem.class] ||
161
+ elem.class.ancestors.lazy.map{|ancestor| @array_encoders_by_klass[ancestor] }.find{|a| a } ||
162
+ @textarray_encoder
163
+ end
164
+
165
+ DEFAULT_TYPE_MAP = {
166
+ TrueClass => [1, 'bool', 'bool'],
167
+ FalseClass => [1, 'bool', 'bool'],
168
+ # We use text format and no type OID for numbers, because setting the OID can lead
169
+ # to unnecessary type conversions on server side.
170
+ Integer => [0, 'int8'],
171
+ Float => [0, 'float8'],
172
+ BigDecimal => [0, 'numeric'],
173
+ Time => [0, 'timestamptz'],
174
+ # We use text format and no type OID for IPAddr, because setting the OID can lead
175
+ # to unnecessary inet/cidr conversions on the server side.
176
+ IPAddr => [0, 'inet'],
177
+ Hash => [0, 'json'],
178
+ Array => :get_array_type,
179
+ BinaryData => [1, 'bytea'],
180
+ }
181
+
182
+ DEFAULT_ARRAY_TYPE_MAP = {
183
+ TrueClass => [0, '_bool'],
184
+ FalseClass => [0, '_bool'],
185
+ Integer => [0, '_int8'],
186
+ String => [0, '_text'],
187
+ Float => [0, '_float8'],
188
+ BigDecimal => [0, '_numeric'],
189
+ Time => [0, '_timestamptz'],
190
+ IPAddr => [0, '_inet'],
191
+ }
192
+
193
+ end
@@ -0,0 +1,81 @@
1
+ # -*- ruby -*-
2
+ # frozen_string_literal: true
3
+
4
+ require 'pg' unless defined?( PG )
5
+
6
+ # Simple set of rules for type casting common PostgreSQL types to Ruby.
7
+ #
8
+ # OIDs of supported type casts are not hard-coded in the sources, but are retrieved from the
9
+ # PostgreSQL's +pg_type+ table in PG::BasicTypeMapForResults.new .
10
+ #
11
+ # Result values are type casted based on the type OID of the given result column.
12
+ #
13
+ # Higher level libraries will most likely not make use of this class, but use their
14
+ # own set of rules to choose suitable encoders and decoders.
15
+ #
16
+ # Example:
17
+ # conn = PG::Connection.new
18
+ # # Assign a default ruleset for type casts of output values.
19
+ # conn.type_map_for_results = PG::BasicTypeMapForResults.new(conn)
20
+ # # Execute a query.
21
+ # res = conn.exec_params( "SELECT $1::INT", ['5'] )
22
+ # # Retrieve and cast the result value. Value format is 0 (text) and OID is 20. Therefore typecasting
23
+ # # is done by PG::TextDecoder::Integer internally for all value retrieval methods.
24
+ # res.values # => [[5]]
25
+ #
26
+ # PG::TypeMapByOid#build_column_map(result) can be used to generate
27
+ # a result independent PG::TypeMapByColumn type map, which can subsequently be used
28
+ # to cast #get_copy_data fields:
29
+ #
30
+ # For the following table:
31
+ # conn.exec( "CREATE TABLE copytable AS VALUES('a', 123, '{5,4,3}'::INT[])" )
32
+ #
33
+ # # Retrieve table OIDs per empty result set.
34
+ # res = conn.exec( "SELECT * FROM copytable LIMIT 0" )
35
+ # # Build a type map for common database to ruby type decoders.
36
+ # btm = PG::BasicTypeMapForResults.new(conn)
37
+ # # Build a PG::TypeMapByColumn with decoders suitable for copytable.
38
+ # tm = btm.build_column_map( res )
39
+ # row_decoder = PG::TextDecoder::CopyRow.new type_map: tm
40
+ #
41
+ # conn.copy_data( "COPY copytable TO STDOUT", row_decoder ) do |res|
42
+ # while row=conn.get_copy_data
43
+ # p row
44
+ # end
45
+ # end
46
+ # This prints the rows with type casted columns:
47
+ # ["a", 123, [5, 4, 3]]
48
+ #
49
+ # See also PG::BasicTypeMapBasedOnResult for the encoder direction and PG::BasicTypeRegistry for the definition of additional types.
50
+ class PG::BasicTypeMapForResults < PG::TypeMapByOid
51
+ include PG::BasicTypeRegistry::Checker
52
+
53
+ class WarningTypeMap < PG::TypeMapInRuby
54
+ def initialize(typenames)
55
+ @already_warned = Hash.new{|h, k| h[k] = {} }
56
+ @typenames_by_oid = typenames
57
+ end
58
+
59
+ def typecast_result_value(result, _tuple, field)
60
+ format = result.fformat(field)
61
+ oid = result.ftype(field)
62
+ unless @already_warned[format][oid]
63
+ warn "Warning: no type cast defined for type #{@typenames_by_oid[oid].inspect} format #{format} with oid #{oid}. Please cast this type explicitly to TEXT to be safe for future changes."
64
+ @already_warned[format][oid] = true
65
+ end
66
+ super
67
+ end
68
+ end
69
+
70
+ def initialize(connection_or_coder_maps, registry: nil)
71
+ @coder_maps = build_coder_maps(connection_or_coder_maps, registry: registry)
72
+
73
+ # Populate TypeMapByOid hash with decoders
74
+ @coder_maps.each_format(:decoder).flat_map{|f| f.coders }.each do |coder|
75
+ add_coder(coder)
76
+ end
77
+
78
+ typenames = @coder_maps.typenames_by_oid
79
+ self.default_type_map = WarningTypeMap.new(typenames)
80
+ end
81
+ end
@@ -0,0 +1,296 @@
1
+ # -*- ruby -*-
2
+ # frozen_string_literal: true
3
+
4
+ require 'pg' unless defined?( PG )
5
+
6
+ # This class defines the mapping between PostgreSQL types and encoder/decoder classes for PG::BasicTypeMapForResults, PG::BasicTypeMapForQueries and PG::BasicTypeMapBasedOnResult.
7
+ #
8
+ # Additional types can be added like so:
9
+ #
10
+ # require 'pg'
11
+ # require 'ipaddr'
12
+ #
13
+ # class InetDecoder < PG::SimpleDecoder
14
+ # def decode(string, tuple=nil, field=nil)
15
+ # IPAddr.new(string)
16
+ # end
17
+ # end
18
+ # class InetEncoder < PG::SimpleEncoder
19
+ # def encode(ip_addr)
20
+ # ip_addr.to_s
21
+ # end
22
+ # end
23
+ #
24
+ # conn = PG.connect
25
+ # regi = PG::BasicTypeRegistry.new.define_default_types
26
+ # regi.register_type(0, 'inet', InetEncoder, InetDecoder)
27
+ # conn.type_map_for_results = PG::BasicTypeMapForResults.new(conn, registry: regi)
28
+ class PG::BasicTypeRegistry
29
+ # An instance of this class stores the coders that should be used for a particular wire format (text or binary)
30
+ # and type cast direction (encoder or decoder).
31
+ #
32
+ # Each coder object is filled with the PostgreSQL type name, OID, wire format and array coders are filled with the base elements_type.
33
+ class CoderMap
34
+ # Hash of text types that don't require quotation, when used within composite types.
35
+ # type.name => true
36
+ DONT_QUOTE_TYPES = %w[
37
+ int2 int4 int8
38
+ float4 float8
39
+ oid
40
+ bool
41
+ date timestamp timestamptz
42
+ ].inject({}){|h,e| h[e] = true; h }
43
+
44
+ def initialize(result, coders_by_name, format, arraycoder)
45
+ coder_map = {}
46
+
47
+ arrays, nodes = result.partition { |row| row['typinput'] == 'array_in' }
48
+
49
+ # populate the base types
50
+ nodes.find_all { |row| coders_by_name.key?(row['typname']) }.each do |row|
51
+ coder = coders_by_name[row['typname']].dup
52
+ coder.oid = row['oid'].to_i
53
+ coder.name = row['typname']
54
+ coder.format = format
55
+ coder_map[coder.oid] = coder
56
+ end
57
+
58
+ if arraycoder
59
+ # populate array types
60
+ arrays.each do |row|
61
+ elements_coder = coder_map[row['typelem'].to_i]
62
+ next unless elements_coder
63
+
64
+ coder = arraycoder.new
65
+ coder.oid = row['oid'].to_i
66
+ coder.name = row['typname']
67
+ coder.format = format
68
+ coder.elements_type = elements_coder
69
+ coder.needs_quotation = !DONT_QUOTE_TYPES[elements_coder.name]
70
+ coder_map[coder.oid] = coder
71
+ end
72
+ end
73
+
74
+ @coders = coder_map.values
75
+ @coders_by_name = @coders.inject({}){|h, t| h[t.name] = t; h }
76
+ @coders_by_oid = @coders.inject({}){|h, t| h[t.oid] = t; h }
77
+ end
78
+
79
+ attr_reader :coders
80
+ attr_reader :coders_by_oid
81
+ attr_reader :coders_by_name
82
+
83
+ def coder_by_name(name)
84
+ @coders_by_name[name]
85
+ end
86
+
87
+ def coder_by_oid(oid)
88
+ @coders_by_oid[oid]
89
+ end
90
+ end
91
+
92
+ # An instance of this class stores CoderMap instances to be used for text and binary wire formats
93
+ # as well as encoder and decoder directions.
94
+ #
95
+ # A PG::BasicTypeRegistry::CoderMapsBundle instance retrieves all type definitions from the PostgreSQL server and matches them with the coder definitions of the global PG::BasicTypeRegistry .
96
+ # It provides 4 separate CoderMap instances for the combinations of the two formats and directions.
97
+ #
98
+ # A PG::BasicTypeRegistry::CoderMapsBundle instance can be used to initialize an instance of
99
+ # * PG::BasicTypeMapForResults
100
+ # * PG::BasicTypeMapForQueries
101
+ # * PG::BasicTypeMapBasedOnResult
102
+ # by passing it instead of the connection object like so:
103
+ #
104
+ # conn = PG::Connection.new
105
+ # maps = PG::BasicTypeRegistry::CoderMapsBundle.new(conn)
106
+ # conn.type_map_for_results = PG::BasicTypeMapForResults.new(maps)
107
+ #
108
+ class CoderMapsBundle
109
+ attr_reader :typenames_by_oid
110
+
111
+ def initialize(connection, registry: nil)
112
+ registry ||= DEFAULT_TYPE_REGISTRY
113
+
114
+ result = connection.exec(<<-SQL).to_a
115
+ SELECT t.oid, t.typname, t.typelem, t.typdelim, ti.proname AS typinput
116
+ FROM pg_type as t
117
+ JOIN pg_proc as ti ON ti.oid = t.typinput
118
+ SQL
119
+
120
+ @maps = [
121
+ [0, :encoder, PG::TextEncoder::Array],
122
+ [0, :decoder, PG::TextDecoder::Array],
123
+ [1, :encoder, nil],
124
+ [1, :decoder, nil],
125
+ ].inject([]) do |h, (format, direction, arraycoder)|
126
+ coders = registry.coders_for(format, direction) || {}
127
+ h[format] ||= {}
128
+ h[format][direction] = CoderMap.new(result, coders, format, arraycoder)
129
+ h
130
+ end
131
+
132
+ @typenames_by_oid = result.inject({}){|h, t| h[t['oid'].to_i] = t['typname']; h }
133
+ end
134
+
135
+ def each_format(direction)
136
+ @maps.map { |f| f[direction] }
137
+ end
138
+
139
+ def map_for(format, direction)
140
+ @maps[format][direction]
141
+ end
142
+ end
143
+
144
+ module Checker
145
+ ValidFormats = { 0 => true, 1 => true }
146
+ ValidDirections = { :encoder => true, :decoder => true }
147
+
148
+ protected def check_format_and_direction(format, direction)
149
+ raise(ArgumentError, "Invalid format value %p" % format) unless ValidFormats[format]
150
+ raise(ArgumentError, "Invalid direction %p" % direction) unless ValidDirections[direction]
151
+ end
152
+
153
+ protected def build_coder_maps(conn_or_maps, registry: nil)
154
+ if conn_or_maps.is_a?(PG::BasicTypeRegistry::CoderMapsBundle)
155
+ raise ArgumentError, "registry argument must be given to CoderMapsBundle" if registry
156
+ conn_or_maps
157
+ else
158
+ PG::BasicTypeRegistry::CoderMapsBundle.new(conn_or_maps, registry: registry)
159
+ end
160
+ end
161
+ end
162
+
163
+ include Checker
164
+
165
+ def initialize
166
+ # The key of these hashs maps to the `typname` column from the table pg_type.
167
+ @coders_by_name = []
168
+ end
169
+
170
+ # Retrieve a Hash of all en- or decoders for a given wire format.
171
+ # The hash key is the name as defined in table +pg_type+.
172
+ # The hash value is the registered coder object.
173
+ def coders_for(format, direction)
174
+ check_format_and_direction(format, direction)
175
+ @coders_by_name[format]&.[](direction)
176
+ end
177
+
178
+ # Register an encoder or decoder instance for casting a PostgreSQL type.
179
+ #
180
+ # Coder#name must correspond to the +typname+ column in the +pg_type+ table.
181
+ # Coder#format can be 0 for text format and 1 for binary.
182
+ def register_coder(coder)
183
+ h = @coders_by_name[coder.format] ||= { encoder: {}, decoder: {} }
184
+ name = coder.name || raise(ArgumentError, "name of #{coder.inspect} must be defined")
185
+ h[:encoder][name] = coder if coder.respond_to?(:encode)
186
+ h[:decoder][name] = coder if coder.respond_to?(:decode)
187
+ end
188
+
189
+ # Register the given +encoder_class+ and/or +decoder_class+ for casting a PostgreSQL type.
190
+ #
191
+ # +name+ must correspond to the +typname+ column in the +pg_type+ table.
192
+ # +format+ can be 0 for text format and 1 for binary.
193
+ def register_type(format, name, encoder_class, decoder_class)
194
+ register_coder(encoder_class.new(name: name, format: format)) if encoder_class
195
+ register_coder(decoder_class.new(name: name, format: format)) if decoder_class
196
+ end
197
+
198
+ # Alias the +old+ type to the +new+ type.
199
+ def alias_type(format, new, old)
200
+ [:encoder, :decoder].each do |ende|
201
+ enc = @coders_by_name[format][ende][old]
202
+ if enc
203
+ @coders_by_name[format][ende][new] = enc
204
+ else
205
+ @coders_by_name[format][ende].delete(new)
206
+ end
207
+ end
208
+ end
209
+
210
+ # Populate the registry with all builtin types of ruby-pg
211
+ def define_default_types
212
+ register_type 0, 'int2', PG::TextEncoder::Integer, PG::TextDecoder::Integer
213
+ alias_type 0, 'int4', 'int2'
214
+ alias_type 0, 'int8', 'int2'
215
+ alias_type 0, 'oid', 'int2'
216
+
217
+ register_type 0, 'numeric', PG::TextEncoder::Numeric, PG::TextDecoder::Numeric
218
+ register_type 0, 'text', PG::TextEncoder::String, PG::TextDecoder::String
219
+ alias_type 0, 'varchar', 'text'
220
+ alias_type 0, 'char', 'text'
221
+ alias_type 0, 'bpchar', 'text'
222
+ alias_type 0, 'xml', 'text'
223
+ alias_type 0, 'name', 'text'
224
+
225
+ # FIXME: why are we keeping these types as strings?
226
+ # alias_type 'tsvector', 'text'
227
+ # alias_type 'interval', 'text'
228
+ # alias_type 'macaddr', 'text'
229
+ # alias_type 'uuid', 'text'
230
+ #
231
+ # register_type 'money', OID::Money.new
232
+ # There is no PG::TextEncoder::Bytea, because it's simple and more efficient to send bytea-data
233
+ # in binary format, either with PG::BinaryEncoder::Bytea or in Hash param format.
234
+ register_type 0, 'bytea', nil, PG::TextDecoder::Bytea
235
+ register_type 0, 'bool', PG::TextEncoder::Boolean, PG::TextDecoder::Boolean
236
+ # register_type 'bit', OID::Bit.new
237
+ # register_type 'varbit', OID::Bit.new
238
+
239
+ register_type 0, 'float4', PG::TextEncoder::Float, PG::TextDecoder::Float
240
+ alias_type 0, 'float8', 'float4'
241
+
242
+ register_type 0, 'timestamp', PG::TextEncoder::TimestampWithoutTimeZone, PG::TextDecoder::TimestampWithoutTimeZone
243
+ register_type 0, 'timestamptz', PG::TextEncoder::TimestampWithTimeZone, PG::TextDecoder::TimestampWithTimeZone
244
+ register_type 0, 'date', PG::TextEncoder::Date, PG::TextDecoder::Date
245
+ # register_type 'time', OID::Time.new
246
+ #
247
+ # register_type 'path', OID::Text.new
248
+ # register_type 'point', OID::Point.new
249
+ # register_type 'polygon', OID::Text.new
250
+ # register_type 'circle', OID::Text.new
251
+ # register_type 'hstore', OID::Hstore.new
252
+ register_type 0, 'json', PG::TextEncoder::JSON, PG::TextDecoder::JSON
253
+ alias_type 0, 'jsonb', 'json'
254
+ # register_type 'citext', OID::Text.new
255
+ # register_type 'ltree', OID::Text.new
256
+ #
257
+ register_type 0, 'inet', PG::TextEncoder::Inet, PG::TextDecoder::Inet
258
+ alias_type 0, 'cidr', 'inet'
259
+
260
+
261
+
262
+ register_type 1, 'int2', PG::BinaryEncoder::Int2, PG::BinaryDecoder::Integer
263
+ register_type 1, 'int4', PG::BinaryEncoder::Int4, PG::BinaryDecoder::Integer
264
+ register_type 1, 'int8', PG::BinaryEncoder::Int8, PG::BinaryDecoder::Integer
265
+ alias_type 1, 'oid', 'int2'
266
+
267
+ register_type 1, 'text', PG::BinaryEncoder::String, PG::BinaryDecoder::String
268
+ alias_type 1, 'varchar', 'text'
269
+ alias_type 1, 'char', 'text'
270
+ alias_type 1, 'bpchar', 'text'
271
+ alias_type 1, 'xml', 'text'
272
+ alias_type 1, 'name', 'text'
273
+
274
+ register_type 1, 'bytea', PG::BinaryEncoder::Bytea, PG::BinaryDecoder::Bytea
275
+ register_type 1, 'bool', PG::BinaryEncoder::Boolean, PG::BinaryDecoder::Boolean
276
+ register_type 1, 'float4', nil, PG::BinaryDecoder::Float
277
+ register_type 1, 'float8', nil, PG::BinaryDecoder::Float
278
+ register_type 1, 'timestamp', nil, PG::BinaryDecoder::TimestampUtc
279
+ register_type 1, 'timestamptz', nil, PG::BinaryDecoder::TimestampUtcToLocal
280
+
281
+ self
282
+ end
283
+
284
+ # @private
285
+ DEFAULT_TYPE_REGISTRY = PG::BasicTypeRegistry.new.define_default_types
286
+
287
+ # Delegate class method calls to DEFAULT_TYPE_REGISTRY
288
+ class << self
289
+ %i[ register_coder register_type alias_type ].each do |meth|
290
+ define_method(meth) do |*args|
291
+ warn "PG::BasicTypeRegistry.#{meth} is deprecated. Please use your own instance by PG::BasicTypeRegistry.new instead!"
292
+ DEFAULT_TYPE_REGISTRY.send(meth, *args)
293
+ end
294
+ end
295
+ end
296
+ end
@@ -0,0 +1,23 @@
1
+ # -*- ruby -*-
2
+ # frozen_string_literal: true
3
+
4
+ module PG
5
+ module BinaryDecoder
6
+ # Convenience classes for timezone options
7
+ class TimestampUtc < Timestamp
8
+ def initialize(params={})
9
+ super(params.merge(flags: PG::Coder::TIMESTAMP_DB_UTC | PG::Coder::TIMESTAMP_APP_UTC))
10
+ end
11
+ end
12
+ class TimestampUtcToLocal < Timestamp
13
+ def initialize(params={})
14
+ super(params.merge(flags: PG::Coder::TIMESTAMP_DB_UTC | PG::Coder::TIMESTAMP_APP_LOCAL))
15
+ end
16
+ end
17
+ class TimestampLocal < Timestamp
18
+ def initialize(params={})
19
+ super(params.merge(flags: PG::Coder::TIMESTAMP_DB_LOCAL | PG::Coder::TIMESTAMP_APP_LOCAL))
20
+ end
21
+ end
22
+ end
23
+ end # module PG