quill-sql 0.1.8 → 0.2.0

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.
@@ -1,9 +1,11 @@
1
1
  require 'redis'
2
2
  require 'json'
3
3
  require_relative 'db_helper'
4
+ require_relative '../utils/report_error'
4
5
 
5
6
  class CachedConnection
6
7
  DEFAULT_CACHE_TTL = 24 * 60 * 60 # 24 hours in seconds
8
+ REDIS_CONNECT_TIMEOUT = 5 # seconds; a bad host/port/password degrades to "no cache"
7
9
 
8
10
  attr_reader :database_type, :pool, :ttl, :cache
9
11
  attr_reader :closed
@@ -14,30 +16,144 @@ class CachedConnection
14
16
  @pool = DatabaseHelper.connect_to_database(database_type, config)
15
17
  @tenant_ids = nil
16
18
  @ttl = cache_config[:ttl] || DEFAULT_CACHE_TTL
17
- @cache = get_cache(cache_config)
19
+ begin
20
+ @cache = get_cache(cache_config)
21
+ rescue StandardError
22
+ DatabaseHelper.disconnect_from_database(@database_type, @pool)
23
+ raise
24
+ end
18
25
  @closed = false
26
+ @cache_mutex = Mutex.new
19
27
  end
20
28
 
21
- def query(text)
22
- raise "Connection is closed" if @closed
29
+ def query(text, overwrite_cache = false)
30
+ cache = cache_client
31
+ raise 'Connection is closed' if @closed
23
32
 
24
- if @cache.nil?
33
+ if cache.nil?
25
34
  return DatabaseHelper.run_query_by_database(@database_type, @pool, text)
26
35
  end
27
36
 
28
- key = "#{@tenant_ids}:#{text}"
29
- cached_result = @cache.get(key)
37
+ # Node keys query results by the SQL text alone.
38
+ key = text
39
+ cached_result = overwrite_cache ? nil : get_cached_value(key)
30
40
 
31
41
  if cached_result
32
- JSON.parse(cached_result)
33
- else
34
- new_result = DatabaseHelper.run_query_by_database(@database_type, @pool, text)
35
- new_result_string = JSON.generate(new_result)
36
- @cache.set(key, new_result_string, "EX", DEFAULT_CACHE_TTL)
37
- new_result
42
+ begin
43
+ parsed = JSON.parse(cached_result)
44
+ # same shape as a cache miss: symbol keys at the top level and in fields, string keys in rows
45
+ return {
46
+ fields: (parsed['fields'] || []).map { |field| field.transform_keys(&:to_sym) },
47
+ rows: parsed['rows'] || []
48
+ }
49
+ rescue JSON::ParserError
50
+ # corrupted entry; drop it and fall through to the database
51
+ delete_cached_value(key)
52
+ end
38
53
  end
54
+
55
+ new_result = DatabaseHelper.run_query_by_database(@database_type, @pool, text)
56
+ set_cached_value(key, JSON.generate(new_result))
57
+ new_result
39
58
  rescue StandardError => e
40
- raise StandardError, e.message
59
+ raise ReportError.report_request(ReportError.origin_of(@database_type), 'query', e)
60
+ end
61
+
62
+ # Returns nil on a miss *or* when Redis is unavailable; the cache must never fail a query.
63
+ def get_cached_value(key)
64
+ cache = cache_client
65
+ return nil if cache.nil?
66
+
67
+ cache.get(key)
68
+ rescue Redis::BaseError => e
69
+ ReportError.report_background('cache', 'redis:get', e)
70
+ nil
71
+ end
72
+
73
+ def set_cached_value(key, value)
74
+ cache = cache_client
75
+ return if cache.nil?
76
+
77
+ cache.set(key, value, ex: @ttl)
78
+ rescue Redis::BaseError => e
79
+ ReportError.report_background('cache', 'redis:set', e)
80
+ end
81
+
82
+ def delete_cached_value(key)
83
+ cache = cache_client
84
+ return if cache.nil?
85
+
86
+ cache.del(key)
87
+ rescue Redis::BaseError => e
88
+ ReportError.report_background('cache', 'redis:delete', e)
89
+ end
90
+
91
+ # Legacy Redis set key holding cache keys under `tag` (still cleared on invalidation).
92
+ def self.tag_index_key(tag)
93
+ "quill:post-tags:#{tag}"
94
+ end
95
+
96
+ # Expiry-scored Redis ZSET holding cache keys recorded under `tag`.
97
+ def self.tag_zset_key(tag)
98
+ "quill:post-tags:v2:#{tag}"
99
+ end
100
+
101
+ # Indexes `key` under each tag with its expiry timestamp so expired members are pruned
102
+ # on cache misses instead of growing unboundedly in Redis.
103
+ def tag_cached_value(key, tags)
104
+ cache = cache_client
105
+ return if cache.nil? || tags.empty?
106
+
107
+ use_zset = cache.respond_to?(:zadd) && cache.respond_to?(:zremrangebyscore)
108
+ now = Time.now.to_i
109
+ tags.each do |tag|
110
+ if use_zset
111
+ z_key = CachedConnection.tag_zset_key(tag)
112
+ if cache.respond_to?(:pipelined)
113
+ cache.pipelined do |pipe|
114
+ pipe.zadd(z_key, now + @ttl, key)
115
+ pipe.zremrangebyscore(z_key, '-inf', now)
116
+ pipe.expire(z_key, @ttl)
117
+ end
118
+ else
119
+ cache.zadd(z_key, now + @ttl, key)
120
+ cache.zremrangebyscore(z_key, '-inf', now)
121
+ cache.expire(z_key, @ttl)
122
+ end
123
+ else
124
+ index_key = CachedConnection.tag_index_key(tag)
125
+ cache.sadd(index_key, key)
126
+ cache.expire(index_key, @ttl)
127
+ end
128
+ end
129
+ rescue Redis::BaseError => e
130
+ ReportError.report_background('cache', 'redis:tag', e)
131
+ end
132
+
133
+ # Deletes every cached value indexed under any of `tags`, then the indexes themselves.
134
+ def invalidate_cached_tags(tags)
135
+ cache = cache_client
136
+ return if cache.nil? || tags.empty?
137
+
138
+ now = Time.now.to_i
139
+ tags.each do |tag|
140
+ if cache.respond_to?(:zrangebyscore)
141
+ z_key = CachedConnection.tag_zset_key(tag)
142
+ members = cache.zrangebyscore(z_key, "(#{now}", '+inf')
143
+ cache.del(*members, z_key) unless members.empty?
144
+ elsif cache.respond_to?(:zrange)
145
+ z_key = CachedConnection.tag_zset_key(tag)
146
+ members = cache.zrange(z_key, 0, -1)
147
+ cache.del(*members, z_key) unless members.empty?
148
+ end
149
+ if cache.respond_to?(:smembers)
150
+ legacy_key = CachedConnection.tag_index_key(tag)
151
+ keys = cache.smembers(legacy_key)
152
+ cache.del(*keys, legacy_key) unless keys.empty?
153
+ end
154
+ end
155
+ rescue Redis::BaseError => e
156
+ ReportError.report_background('cache', 'redis:invalidate', e)
41
157
  end
42
158
 
43
159
  def get_pool
@@ -45,16 +161,70 @@ class CachedConnection
45
161
  end
46
162
 
47
163
  def close
164
+ cache = @cache_mutex.synchronize do
165
+ return if @closed
166
+
167
+ @closed = true
168
+ current = @cache
169
+ @cache = nil
170
+ current
171
+ end
48
172
  DatabaseHelper.disconnect_from_database(@database_type, @pool)
49
- @closed = true
173
+ return if cache.nil?
174
+
175
+ begin
176
+ cache.close if cache.respond_to?(:close)
177
+ rescue StandardError => e
178
+ ReportError.report_background('cache', 'redis:disconnect', e)
179
+ end
50
180
  end
51
181
 
52
182
  private
53
183
 
184
+ # The client this call will use. close clears @cache under the same mutex,
185
+ # so a command already in flight keeps its client and the next one sees nil.
186
+ def cache_client
187
+ @cache_mutex.synchronize { @closed ? nil : @cache }
188
+ end
189
+
54
190
  def get_cache(config)
55
- return nil unless config[:cacheType]&.match?(/^redis(s)?$/)
191
+ cache_type = config[:cacheType] || config[:cache_type]
192
+ return nil unless cache_type.to_s.match?(/^redis(s)?$/)
56
193
 
57
- redis_url = "#{config[:cacheType]}://#{config[:username]}:#{config[:password]}@#{config[:host]}:#{config[:port]}"
58
- Redis.new(url: redis_url)
194
+ host = config[:host].to_s
195
+ options = {
196
+ connect_timeout: REDIS_CONNECT_TIMEOUT,
197
+ timeout: REDIS_CONNECT_TIMEOUT,
198
+ reconnect_attempts: 1
199
+ }
200
+ if host.include?('://')
201
+ options[:url] = host
202
+ else
203
+ options[:host] = host
204
+ options[:port] = (config[:port] || 6379).to_i
205
+ options[:ssl] = true if cache_type == 'rediss'
206
+ end
207
+ # Only send AUTH when credentials were actually supplied; "redis://:@host" makes the client
208
+ # AUTH with an empty password, which Redis rejects.
209
+ username = config[:username].to_s
210
+ password = config[:password].to_s
211
+ options[:username] = username unless username.empty?
212
+ options[:password] = password unless password.empty?
213
+
214
+ client = Redis.new(**options)
215
+ begin
216
+ client.ping
217
+ client
218
+ rescue Redis::BaseError, SystemCallError => e
219
+ begin
220
+ client.close if client.respond_to?(:close)
221
+ rescue StandardError
222
+ nil
223
+ end
224
+ raise e
225
+ end
226
+ rescue Redis::BaseError, SystemCallError => e
227
+ ReportError.report_background('cache', 'redis:connect', e)
228
+ nil
59
229
  end
60
230
  end
@@ -0,0 +1,60 @@
1
+ # Civil-from-days conversion (Howard Hinnant) and pre-rendered ISO pieces.
2
+ # Engines use this instead of allocating Date/Time just to print a timestamp.
3
+ module CivilTime
4
+ ISO_YEAR = (0..9999).map { |number| format('%04d', number) }.freeze
5
+ ISO_2 = (0..59).map { |number| format('%02d', number) }.freeze
6
+ ISO_3 = (0..999).map { |number| format('%03d', number) }.freeze
7
+
8
+ module_function
9
+
10
+ # Toward-zero division. Ruby's Integer#/ floors, and the calendar
11
+ # algorithm needs the C++ behavior for dates before year 0.
12
+ def trunc_div(number, divisor)
13
+ quotient = number / divisor
14
+ remainder = number % divisor
15
+ return quotient if remainder.zero? || (number.negative? == divisor.negative?)
16
+
17
+ quotient + 1
18
+ end
19
+
20
+ def days_from_civil(year, month, day)
21
+ year -= 1 if month <= 2
22
+ era = year / 400
23
+ yoe = year - era * 400
24
+ doy = (153 * (month + (month > 2 ? -3 : 9)) + 2) / 5 + day - 1
25
+ doe = yoe * 365 + yoe / 4 - yoe / 100 + doy
26
+ era * 146097 + doe - 719468
27
+ end
28
+
29
+ # Dates we format are after year 0, so every division here is of a
30
+ # non-negative integer and Ruby's floor division matches trunc-toward-zero.
31
+ def civil_from_days(z)
32
+ z += 719468
33
+ era = z / 146097
34
+ doe = z - era * 146097
35
+ yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365
36
+ year = yoe + era * 400
37
+ doy = doe - (365 * yoe + yoe / 4 - yoe / 100)
38
+ mp = (5 * doy + 2) / 153
39
+ day = doy - (153 * mp + 2) / 5 + 1
40
+ month = mp < 10 ? mp + 3 : mp - 9
41
+ year += 1 if month <= 2
42
+ [year, month, day]
43
+ end
44
+
45
+ def epoch_parts(seconds)
46
+ days, second_of_day = seconds.divmod(86_400)
47
+ hour, remainder = second_of_day.divmod(3600)
48
+ minute, second = remainder.divmod(60)
49
+ year, month, day = civil_from_days(days)
50
+ [year, month, day, hour, minute, second]
51
+ end
52
+
53
+ def iso_date(year, month, day)
54
+ "#{ISO_YEAR[year]}-#{ISO_2[month]}-#{ISO_2[day]}"
55
+ end
56
+
57
+ def iso_utc(year, month, day, hour, minute, second, milli)
58
+ "#{ISO_YEAR[year]}-#{ISO_2[month]}-#{ISO_2[day]}T#{ISO_2[hour]}:#{ISO_2[minute]}:#{ISO_2[second]}.#{ISO_3[milli]}Z"
59
+ end
60
+ end
data/lib/db/clickhouse.rb CHANGED
@@ -1,9 +1,22 @@
1
1
  require 'uri'
2
2
  require 'json'
3
3
  require 'click_house'
4
- require 'active_support/inflector'
4
+ require_relative '../utils/report_error'
5
5
 
6
6
  module ClickHouseHelper
7
+ # @clickhouse/client's parseError. The DB::Exception text is the error
8
+ # message both the Node and Python SDKs surface.
9
+ ERROR_RE = /(Code|Error): (?<code>\d+).*Exception: (?<message>.+)\((?<type>(?=.+[A-Z]{3})[A-Z0-9_]+?)\)/m
10
+
11
+ class ClickHouseError < StandardError
12
+ attr_reader :code, :type
13
+
14
+ def initialize(message, code, type)
15
+ super(message)
16
+ @code = code
17
+ @type = type
18
+ end
19
+ end
7
20
  # Constants
8
21
  CLICKHOUSE_PG_TYPE_MAP = {
9
22
  # Signed Integer Types and Aliases
@@ -138,8 +151,8 @@ module ClickHouseHelper
138
151
  return CLICKHOUSE_PG_TYPE_MAP['Enum8'] if normalized_type.start_with?('Enum8(')
139
152
  return CLICKHOUSE_PG_TYPE_MAP['Enum16'] if normalized_type.start_with?('Enum16(')
140
153
 
141
- # Handle Decimal types
142
- if normalized_type.match?(/^Decimal(\d*)?\(/)
154
+ # Handle Decimal types. Same prefixes as Node; a bare Decimal99( falls through.
155
+ if %w[Decimal( Decimal32( Decimal64( Decimal128( Decimal256(].any? { |prefix| normalized_type.start_with?(prefix) }
143
156
  return CLICKHOUSE_PG_TYPE_MAP['Decimal']
144
157
  end
145
158
 
@@ -160,7 +173,7 @@ module ClickHouseHelper
160
173
  lookup_type = CLICKHOUSE_PG_TYPE_MAP.keys.find { |key| key.downcase == normalized_type.downcase }
161
174
  return CLICKHOUSE_PG_TYPE_MAP[lookup_type] if lookup_type
162
175
 
163
- warn "Unknown ClickHouse type: #{type}. Defaulting to VARCHAR."
176
+ ReportError.report_background('clickhouse', 'type', "Unknown ClickHouse type: #{type}. Defaulting to VARCHAR.")
164
177
  1043 # Default to Varchar
165
178
  end
166
179
 
@@ -180,24 +193,40 @@ module ClickHouseHelper
180
193
  client.close if client.respond_to?(:close)
181
194
  end
182
195
 
196
+ def parse_clickhouse_error(error)
197
+ match = error.to_s.match(ERROR_RE)
198
+ if match
199
+ return ClickHouseError.new(match[:message], match[:code], match[:type])
200
+ end
201
+
202
+ return error if error.is_a?(Exception)
203
+
204
+ RuntimeError.new(error.to_s)
205
+ end
206
+
183
207
  def run_query_clickhouse(sql, client)
184
- # Need to include FORMAT JSON at the end of query to include clickhouse metadata
185
- # Remove existing FORMAT from query, remove ending semicolon, and add FORMAT JSON
186
- response = response = client.execute(sql.gsub(/\s*FORMAT\s+\w+/i, '').gsub(/;\s*$/, '') + ' FORMAT JSON')
187
-
188
- data = response.body
189
-
208
+ # Node's client.query({ format: "JSON" }) strips a trailing semicolon and
209
+ # asks ClickHouse for JSON. Rows are that JSON `data` array, untouched:
210
+ # 64-bit integers and dates stay strings, floats and decimals stay numbers.
211
+ response = client.execute(sql.to_s.gsub(/\s*FORMAT\s+\w+/i, '').gsub(/;\s*$/, '') + ' FORMAT JSON')
212
+ data = clickhouse_json_body(response.body)
213
+
190
214
  fields = data['meta']&.map do |field|
191
215
  {
192
216
  name: field['name'],
193
217
  dataTypeID: parse_clickhouse_type(field['type'])
194
218
  }
195
219
  end || []
196
-
220
+
197
221
  {
198
222
  fields: fields,
199
223
  rows: data['data']
200
224
  }
225
+ rescue StandardError => e
226
+ parsed = parse_clickhouse_error(e)
227
+ raise if parsed.equal?(e)
228
+
229
+ raise parsed
201
230
  end
202
231
 
203
232
  def get_schemas_clickhouse(client)
@@ -243,16 +272,16 @@ module ClickHouseHelper
243
272
  end
244
273
 
245
274
  def get_foreign_keys_clickhouse(client, schema_name, table_name, primary_key)
246
- depluralized_table_name = table_name.singularize
247
-
275
+ depluralized_table_name = clickhouse_depluralize(table_name)
276
+ capitalized_key = clickhouse_capitalize(primary_key)
277
+
248
278
  sql = <<~SQL
249
- SELECT column_name
250
- FROM information_schema.columns
251
- WHERE table_schema = '#{schema_name}'
252
- AND table_name != '#{table_name}'
253
- AND (column_name = '#{primary_key}'
254
- OR column_name = '#{depluralized_table_name}_#{primary_key}'
255
- OR column_name = '#{depluralized_table_name}#{primary_key.capitalize}')
279
+ SELECT column_name FROM information_schema.columns
280
+ WHERE table_schema = '#{schema_name}'
281
+ and table_name != '#{table_name}'
282
+ and (column_name = '#{primary_key}'
283
+ or column_name = '#{depluralized_table_name}_#{primary_key}'
284
+ or column_name = '#{depluralized_table_name}#{capitalized_key}')
256
285
  SQL
257
286
 
258
287
  results = run_query_clickhouse(sql, client)
@@ -263,15 +292,14 @@ module ClickHouseHelper
263
292
 
264
293
  if foreign_keys.empty?
265
294
  sql = <<~SQL
266
- SELECT column_name
267
- FROM information_schema.columns
268
- WHERE table_schema = '#{schema_name}'
269
- AND table_name != '#{table_name}'
270
- AND (column_name LIKE '#{table_name}%'
271
- OR column_name LIKE '%\_id'
272
- OR column_name LIKE '%Id'
273
- OR column_name LIKE '%\_#{primary_key}'
274
- OR column_name LIKE '%#{primary_key.capitalize}')
295
+ SELECT column_name FROM information_schema.columns
296
+ WHERE table_schema = '#{schema_name}'
297
+ and table_name != '#{table_name}'
298
+ and (column_name like '#{table_name}%'
299
+ or column_name like '%\\_id'
300
+ or column_name like '%Id'
301
+ or column_name like '%\\_#{primary_key}'
302
+ or column_name like '%#{capitalized_key}')
275
303
  SQL
276
304
 
277
305
  results = run_query_clickhouse(sql, client)
@@ -281,42 +309,130 @@ module ClickHouseHelper
281
309
  foreign_keys
282
310
  end
283
311
 
284
- def get_schema_column_info_clickhouse(client, schema_name, table_names)
285
- table_names.map do |table_name|
312
+ def get_schema_column_info_clickhouse(client, _schema_name, table_names)
313
+ table_names.map do |table|
314
+ table_schema, table_name = table_identity(table)
286
315
  query = <<~SQL
287
- SELECT
288
- name as "column_name",
289
- type as "field_type"
316
+ SELECT
317
+ name as "columnName",
318
+ type as "fieldType"
290
319
  FROM system.columns
291
- WHERE database = '#{table_name[:schemaName]}'
292
- AND table = '#{table_name[:tableName]}'
320
+ WHERE database = '#{table_schema}'
321
+ AND table = '#{table_name}'
293
322
  SQL
294
323
 
295
324
  results = run_query_clickhouse(query, client)
296
325
  {
297
- tableName: "#{table_name[:schemaName]}.#{table_name[:tableName]}",
298
- displayName: "#{table_name[:schemaName]}.#{table_name[:tableName]}",
326
+ tableName: "#{table_schema}.#{table_name}",
327
+ displayName: "#{table_schema}.#{table_name}",
299
328
  columns: results[:rows].map do |row|
300
- type_oid = parse_clickhouse_type(row['field_type'])
301
329
  {
302
- columnName: row['column_name'],
303
- displayName: row['column_name'],
304
- dataTypeID: type_oid,
305
- fieldType: row['field_type']
330
+ columnName: row['columnName'],
331
+ displayName: row['columnName'],
332
+ dataTypeID: parse_clickhouse_type(row['fieldType']),
333
+ fieldType: row['fieldType']
306
334
  }
307
335
  end
308
336
  }
309
337
  end
310
338
  end
311
339
 
340
+ # `http[s]://user:password@host:8123` -> `{url, username, password}`.
341
+ # Ruby's URI assigns the scheme default (80/443) when the URL omits a port;
342
+ # Node and Python only include a port that was written in the URL. Credentials
343
+ # stay percent-encoded, matching `new URL()`.
312
344
  def format_clickhouse_config(connection_string)
313
345
  parsed = URI.parse(connection_string)
314
-
346
+ raise ArgumentError, 'Invalid URL' if parsed.scheme.to_s.empty? || parsed.host.to_s.empty?
347
+
348
+ url = "#{parsed.scheme}://#{parsed.host}"
349
+ port = explicit_port(connection_string)
350
+ url = "#{url}:#{port}" if port
351
+ username, password = raw_credentials(connection_string)
315
352
  {
316
- url: "#{parsed.scheme}://#{parsed.host}:#{parsed.port}",
317
- username: parsed.user || 'default',
318
- password: parsed.password || ''
353
+ url: url,
354
+ username: username.nil? || username.empty? ? 'default' : username,
355
+ password: password || ''
319
356
  }
357
+ rescue URI::InvalidURIError
358
+ raise ArgumentError, 'Invalid URL'
359
+ end
360
+
361
+ private
362
+
363
+ def clickhouse_json_body(body)
364
+ return {} if body.nil?
365
+ return JSON.parse(body) if body.is_a?(String)
366
+
367
+ body
368
+ end
369
+
370
+ # Node's textProcessing.depluralize, not ActiveSupport's singularize.
371
+ def clickhouse_depluralize(text)
372
+ return text[0..-4] + 'y' if text.end_with?('ies')
373
+ return text[0..-2] if text.end_with?('s')
374
+
375
+ text
376
+ end
377
+
378
+ def clickhouse_capitalize(text)
379
+ return text if text.nil? || text.empty?
380
+
381
+ text[0].upcase + text[1..]
382
+ end
383
+
384
+ def table_identity(table)
385
+ schema_name = table[:schemaName] || table['schemaName'] || table[:schema_name] || table['schema_name']
386
+ table_name = table[:tableName] || table['tableName'] || table[:table_name] || table['table_name']
387
+ [schema_name, table_name]
388
+ end
389
+
390
+ def explicit_port(connection_string)
391
+ rest = connection_string.sub(%r{\A[a-z][a-z0-9+.-]*://}i, '')
392
+ rest = rest.sub(/\A[^@]*@/, '')
393
+ match = rest.match(%r{\A\[[^\]]+\]:(\d+)}) || rest.match(%r{\A[^/:]*:(\d+)})
394
+ match && match[1]
395
+ end
396
+
397
+ def raw_credentials(connection_string)
398
+ rest = connection_string.sub(%r{\A[a-z][a-z0-9+.-]*://}i, '')
399
+ return [nil, nil] unless rest.include?('@')
400
+
401
+ userinfo = rest.split('@', 2).first
402
+ userinfo.split(':', 2)
403
+ end
404
+ end
405
+
406
+ # click_house 2.1.2 calls JSON.parse(body, options_hash). json 3 only accepts
407
+ # keywords, so that raises "given 2, expected 1" on every JSON response.
408
+ # decimal_class: BigDecimal turns 1.5 into a BigDecimal, and JSON.generate
409
+ # then emits the string "0.15e1". Node keeps ClickHouse's JSON numbers.
410
+ module KeywordJsonParse
411
+ def on_complete(env)
412
+ return unless content_type?(env, content_type)
413
+ return if env.body.nil? || env.body.strip.empty?
414
+ # The body of an error is ClickHouse's message, which RaiseError raises.
415
+ return if env[:response_headers].key?(ClickHouse::Middleware::RaiseError::EXCEPTION_CODE_HEADER)
416
+
417
+ options = config.json_load_options
418
+ options = options.transform_keys(&:to_sym) if options.respond_to?(:transform_keys)
419
+ options = options.reject { |key, _| key == :decimal_class }
420
+ env.body = JSON.parse(env.body, **options)
320
421
  end
321
422
  end
322
- end
423
+
424
+ # click_house logs the SQL with CGI.parse. Ruby 4 removed that method.
425
+ module QueryStringParse
426
+ private
427
+
428
+ def query(env)
429
+ return env.request_body if env.method == :get
430
+
431
+ text = URI.decode_www_form(env.url.query.to_s).assoc('query')&.last
432
+ String(text || '[NO QUERY]').chomp
433
+ end
434
+ end
435
+ end
436
+
437
+ ClickHouse::Middleware::ParseJson.prepend(ClickHouseHelper::KeywordJsonParse)
438
+ ClickHouse::Middleware::Logging.prepend(ClickHouseHelper::QueryStringParse)