clickhouse-activerecord 1.6.7 → 1.7.1

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,11 +1,31 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'base64'
4
+ require 'net/http'
3
5
  require 'clickhouse-activerecord/version'
4
6
 
5
7
  module ActiveRecord
6
8
  module ConnectionAdapters
7
9
  module Clickhouse
8
10
  module SchemaStatements
11
+ HTTP_AUTH_QUERY_PARAMS = :query_params
12
+ HTTP_AUTH_BASIC = :basic
13
+ HTTP_AUTH_X_HEADERS = :x_clickhouse_headers
14
+ HTTP_AUTH_TYPES = [HTTP_AUTH_QUERY_PARAMS, HTTP_AUTH_BASIC, HTTP_AUTH_X_HEADERS].freeze
15
+
16
+ # Same threshold as `primary_keys`: before it the primary key is guessed from the column
17
+ # named `id`, which `system.columns` cannot reproduce.
18
+ BULK_SCHEMA_MIN_VERSION = Gem::Version.new('23.4')
19
+
20
+ # Connection-level failures worth a single retry of a read on a fresh connection. With
21
+ # `retry_on_connect_error`, `with_http_session` retries Net::OpenTimeout first, so a read sees
22
+ # it here only when that setting is off.
23
+ RETRYABLE_CONNECTION_ERRORS = [Net::OpenTimeout, EOFError, Errno::ECONNRESET, IOError].freeze
24
+
25
+ # The connection fails to open, before Net::HTTP writes the request. Nothing reached the
26
+ # server, so with `retry_on_connect_error` every statement, a write included, retries once
27
+ # on these.
28
+ CONNECT_ERRORS = [Net::OpenTimeout, SocketError, Errno::ECONNREFUSED].freeze
9
29
 
10
30
  def with_settings(**settings)
11
31
  @block_settings ||= {}
@@ -32,19 +52,15 @@ module ActiveRecord
32
52
  # end
33
53
  # # sends and executes "SELECT * FROM table"
34
54
  def with_response_format(format)
35
- prev_format = @response_format
36
- @response_format = format
55
+ stack = response_format_stack
56
+ stack.push(format)
37
57
  yield
38
58
  ensure
39
- @response_format = prev_format
59
+ stack.pop
40
60
  end
41
61
 
42
- def execute(sql, name = nil, format: @response_format, settings: {})
43
- with_response_format(format) do
44
- log(sql, [adapter_name, name].compact.join(' ')) do
45
- raw_execute(sql, settings: settings)
46
- end
47
- end
62
+ def execute(sql, name = nil, format: response_format, settings: {})
63
+ execute_statement(sql, name, format: format, settings: settings)
48
64
  end
49
65
 
50
66
  def execute_batch(statements, name = nil, **kwargs)
@@ -55,17 +71,13 @@ module ActiveRecord
55
71
 
56
72
  # Execute an SQL query and save the result to a file in stream mode
57
73
  # @return [Tempfile]
58
- def execute_to_file(sql, name = nil, format: @response_format, settings: {})
74
+ def execute_to_file(sql, name = nil, format: response_format, settings: {})
59
75
  with_response_format(format) do
60
76
  log(sql, [adapter_name, 'Stream', name].compact.join(' ')) do
61
- statement = Statement.new(sql, format: @response_format)
77
+ statement = Statement.new(sql, format: response_format)
62
78
  result = nil
63
- @lock.synchronize do
64
- req = Net::HTTP::Post.new("/?#{settings_params(settings)}", {
65
- 'Content-Type' => 'application/x-www-form-urlencoded',
66
- 'User-Agent' => ClickhouseAdapter::USER_AGENT,
67
- })
68
- @connection.start unless @connection.started?
79
+ with_http_session do
80
+ req = Net::HTTP::Post.new("/?#{settings_params(settings)}", build_request_headers)
69
81
  @connection.request(req, statement.formatted_sql) do |response|
70
82
  result = statement.streaming_response(response)
71
83
  end
@@ -82,19 +94,36 @@ module ActiveRecord
82
94
  end
83
95
 
84
96
  def internal_exec_query(sql, name = nil, binds = [], prepare: false, async: false, allow_retry: false)
85
- result = execute(sql, name)
86
- columns = result['meta'].map { |m| m['name'] }
87
- types = {}
88
- result['meta'].each_with_index do |m, i|
89
- # need use column name and index after commit in 7.2:
90
- # https://github.com/rails/rails/commit/24dbf7637b1d5cd6eb3d7100b8d0f6872c3fee3c
91
- types[m['name']] = types[i] = type_map.lookup(m['type'])
97
+ connection_retries = 0
98
+ begin
99
+ # `select_all` reaches here on each cache miss, so this must not clear the cache.
100
+ result = execute_statement(sql, name)
101
+ columns = result['meta'].map { |m| m['name'] }
102
+ types = {}
103
+ result['meta'].each_with_index do |m, i|
104
+ # need use column name and index after commit in 7.2:
105
+ # https://github.com/rails/rails/commit/24dbf7637b1d5cd6eb3d7100b8d0f6872c3fee3c
106
+ types[m['name']] = types[i] = type_map.lookup(m['type'])
107
+ end
108
+ ActiveRecord::Result.new(columns, result['data'], types)
109
+ rescue ActiveRecord::ActiveRecordError => e
110
+ raise e
111
+ rescue Net::ReadTimeout => e
112
+ raise ActiveRecord::AdapterTimeout, "Response: #{e.message}"
113
+ rescue *RETRYABLE_CONNECTION_ERRORS => e
114
+ raise ActiveRecord::ConnectionFailed, "Response: #{e.message}" if connection_retries.positive?
115
+
116
+ connection_retries += 1
117
+ logger&.warn("[clickhouse-activerecord] retrying read query after connection failure (#{e.class}: #{e.message})")
118
+ begin
119
+ reconnect
120
+ rescue StandardError
121
+ nil
122
+ end
123
+ retry
124
+ rescue StandardError => e
125
+ raise ActiveRecord::ActiveRecordError, "Response: #{e.message}"
92
126
  end
93
- ActiveRecord::Result.new(columns, result['data'], types)
94
- rescue ActiveRecord::ActiveRecordError => e
95
- raise e
96
- rescue StandardError => e
97
- raise ActiveRecord::ActiveRecordError, "Response: #{e.message}"
98
127
  end
99
128
 
100
129
  def exec_insert_all(sql, name)
@@ -111,7 +140,7 @@ module ActiveRecord
111
140
  # @link https://clickhouse.com/docs/en/sql-reference/statements/delete
112
141
  def exec_delete(sql, name = nil, _binds = [])
113
142
  log(sql, "#{adapter_name} #{name}") do
114
- statement = Statement.new(sql, format: @response_format)
143
+ statement = Statement.new(sql, format: response_format)
115
144
  res = request(statement)
116
145
  begin
117
146
  data = JSON.parse(res.header['x-clickhouse-summary'])
@@ -147,10 +176,22 @@ module ActiveRecord
147
176
  end
148
177
 
149
178
  def show_create_function(function)
150
- result = do_system_execute("SELECT create_query FROM system.functions WHERE origin = 'SQLUserDefined' AND name = '#{function}'")
179
+ result = do_system_execute("SELECT create_query FROM system.functions WHERE origin = 'SQLUserDefined' AND name = #{quote(function)}")
151
180
  return if result.nil?
152
181
 
153
- result['data'].flatten.first.sub(/\ACREATE FUNCTION/, 'CREATE OR REPLACE FUNCTION')
182
+ result['data'].flatten.first&.sub(/\ACREATE FUNCTION/, 'CREATE OR REPLACE FUNCTION')
183
+ end
184
+
185
+ # The body that `create_function` takes. Raises on a definition in any other shape, because a
186
+ # whole statement passed back as the body fails only when it runs.
187
+ def function_body(function)
188
+ sql = show_create_function(function)
189
+ return if sql.nil?
190
+
191
+ match = sql.match(/\ACREATE OR REPLACE FUNCTION `?#{Regexp.escape(function)}`? AS (.*)\z/m)
192
+ raise ActiveRecord::ActiveRecordError, "Unexpected definition for function #{function}: #{sql}" unless match
193
+
194
+ match[1].strip
154
195
  end
155
196
 
156
197
  def table_options(table)
@@ -233,20 +274,78 @@ module ActiveRecord
233
274
  end
234
275
  end
235
276
 
277
+ # Read the columns and primary keys of every table in one request for the duration of
278
+ # the block. Lookups for a table inside the block are answered from that result; a table
279
+ # the result does not contain still falls back to its own request.
280
+ # Servers older than BULK_SCHEMA_MIN_VERSION keep the request per table.
281
+ def with_bulk_schema_load
282
+ return yield if @bulk_schema || Gem::Version.new(server_version) < BULK_SCHEMA_MIN_VERSION
283
+
284
+ begin
285
+ @bulk_schema = load_bulk_schema
286
+ yield
287
+ ensure
288
+ @bulk_schema = nil
289
+ end
290
+ end
291
+
236
292
  protected
237
293
 
238
294
  def table_structure(table_name)
295
+ return @bulk_schema[:structures][table_name] if @bulk_schema&.dig(:structures, table_name)
296
+
239
297
  result = do_system_execute("DESCRIBE TABLE `#{table_name}`", table_name)
240
298
  data = result['data']
241
299
 
242
- return data unless data.empty?
300
+ raise ActiveRecord::StatementInvalid, "Could not find table '#{table_name}'" if data.empty?
301
+
302
+ data.map do |row|
303
+ Clickhouse::DescribedColumn.new(
304
+ name: row[0],
305
+ sql_type: row[1],
306
+ default_type: row[2],
307
+ default_expression: row[3],
308
+ comment: row[4],
309
+ codec: row[5],
310
+ )
311
+ end
312
+ end
243
313
 
244
- raise ActiveRecord::StatementInvalid, "Could not find table '#{table_name}'"
314
+ def column_definitions(table_name)
315
+ table_structure(table_name).reject(&:ephemeral?)
245
316
  end
246
- alias column_definitions table_structure
247
317
 
248
318
  private
249
319
 
320
+ # One query for all tables. It gives what `DESCRIBE TABLE` gives for the columns (same
321
+ # order, ephemeral columns included) and what `SHOW COLUMNS` gives for the primary keys
322
+ # (alphabetical). Same table filter as `tables`.
323
+ def load_bulk_schema
324
+ result = do_system_execute(<<~SQL.squish, 'SCHEMA')
325
+ SELECT table, name, type, default_kind, default_expression, comment, compression_codec, is_in_primary_key
326
+ FROM system.columns
327
+ WHERE database = currentDatabase() AND table NOT LIKE '.inner_id.%'
328
+ ORDER BY table, position
329
+ SQL
330
+
331
+ schema = { structures: {}, primary_keys: {} }
332
+ result['data'].each do |table, name, type, default_kind, default_expression, comment, codec, in_primary_key|
333
+ (schema[:structures][table] ||= []) << Clickhouse::DescribedColumn.new(
334
+ name: name,
335
+ sql_type: type,
336
+ default_type: default_kind,
337
+ default_expression: default_expression,
338
+ comment: comment,
339
+ # `system.columns` wraps the codec as `CODEC(...)`, `DESCRIBE TABLE` does not
340
+ codec: codec.sub(/\ACODEC\((.*)\)\z/m, '\1'),
341
+ )
342
+ keys = (schema[:primary_keys][table] ||= [])
343
+ keys << name if in_primary_key.to_i == 1
344
+ end
345
+ schema[:primary_keys].each_value(&:sort!)
346
+ schema
347
+ end
348
+
250
349
  def schema_creation
251
350
  Clickhouse::SchemaCreation.new(self)
252
351
  end
@@ -256,22 +355,22 @@ module ActiveRecord
256
355
  end
257
356
 
258
357
  def new_column_from_field(table_name, field, _definitions)
259
- column_name, sql_type, default_type, default_expression = field
260
- type_metadata = fetch_type_metadata(sql_type)
261
- default_value = extract_value_from_default(default_expression, default_type)
262
- default_function = extract_default_function(default_expression)
263
- cast_type = lookup_cast_type(sql_type)
358
+ type_metadata = fetch_type_metadata(field.sql_type)
359
+ default_value = extract_value_from_default(field.default_expression, field.default_type)
360
+ default_function = extract_default_function(field.default_expression)
361
+ cast_type = lookup_cast_type(field.sql_type)
264
362
  default_value = cast_type.cast(default_value)
265
363
 
266
- args = [column_name]
364
+ args = [field.name]
267
365
  args << cast_type if ::ActiveRecord::version >= Gem::Version.new('8.1')
268
- args += [default_value, type_metadata, field[1].include?('Nullable'), default_function]
366
+ args += [default_value, type_metadata, field.sql_type.include?('Nullable'), default_function]
269
367
 
270
- Clickhouse::Column.new(*args, codec: field[5].presence)
368
+ Clickhouse::Column.new(*args, codec: field.codec.presence, default_kind: field.default_type)
271
369
  end
272
370
 
273
371
  def extract_value_from_default(default_expression, default_type)
274
372
  return nil if default_type != 'DEFAULT' || default_expression.blank?
373
+ return nil if default_expression == 'NULL'
275
374
  return nil if has_default_function?(default_expression)
276
375
 
277
376
  # Convert string
@@ -288,8 +387,18 @@ module ActiveRecord
288
387
  (%r{\w+\(.*\)} === default)
289
388
  end
290
389
 
390
+ # `execute` without the cache-clearing wrapper ClickhouseAdapter puts on it. Not named
391
+ # `internal_execute`: Rails calls that with positional binds and `allow_retry:`.
392
+ def execute_statement(sql, name = nil, format: response_format, settings: {})
393
+ with_response_format(format) do
394
+ log(sql, [adapter_name, name].compact.join(' ')) do
395
+ raw_execute(sql, settings: settings)
396
+ end
397
+ end
398
+ end
399
+
291
400
  def raw_execute(sql, settings: {}, except_params: [])
292
- statement = Statement.new(sql, format: @response_format)
401
+ statement = Statement.new(sql, format: response_format)
293
402
  response = request(statement, settings: settings, except_params: except_params)
294
403
  statement.processed_response(response)
295
404
  end
@@ -300,11 +409,37 @@ module ActiveRecord
300
409
  # @param [Array] except_params
301
410
  # @return [Net::HTTPResponse]
302
411
  def request(statement, settings: {}, except_params: [])
303
- @lock.synchronize do
412
+ with_http_session do
304
413
  @connection.post("/?#{settings_params(settings, except: except_params)}",
305
414
  statement.formatted_sql,
306
- 'Content-Type' => 'application/x-www-form-urlencoded',
307
- 'User-Agent' => ClickhouseAdapter::USER_AGENT)
415
+ build_request_headers(include_database: !except_params.include?(:database)))
416
+ end
417
+ end
418
+
419
+ # The connection can fail to open in `start` or, when Net::HTTP reopens a stale keep-alive
420
+ # socket, inside the yielded request. Both happen before Net::HTTP writes the request, so with
421
+ # `retry_on_connect_error` the whole block runs again on a new session.
422
+ #
423
+ # Any other Exception, an interrupt included, also finishes the session: the reply left unread
424
+ # on the keep-alive socket would otherwise answer the next request.
425
+ def with_http_session
426
+ connect_retries = 0
427
+ @lock.synchronize do
428
+ begin
429
+ @connection.start unless @connection.started?
430
+ yield
431
+ rescue *CONNECT_ERRORS => e
432
+ @connection.finish if @connection.started?
433
+ raise unless @retry_on_connect_error
434
+ raise ActiveRecord::ConnectionNotEstablished, "Response: #{e.message}" if connect_retries.positive?
435
+
436
+ connect_retries += 1
437
+ logger&.warn("[clickhouse-activerecord] retrying statement after the connection failed to open (#{e.class}: #{e.message})")
438
+ retry
439
+ rescue Exception
440
+ @connection.finish if @connection.started?
441
+ raise
442
+ end
308
443
  end
309
444
  end
310
445
 
@@ -313,15 +448,57 @@ module ActiveRecord
313
448
  log(sql, "#{name} (system)") { yield }
314
449
  end
315
450
 
451
+ # The response format that should be applied to the next request.
452
+ # Reads the per-thread override pushed by `with_response_format`, falling
453
+ # back to the adapter-level default when no override is in scope.
454
+ def response_format
455
+ stack = response_format_stack
456
+ stack.empty? ? @default_response_format : stack.last
457
+ end
458
+
459
+ def response_format_stack
460
+ key = (@response_format_stack_key ||= :"clickhouse_response_format_stack_#{object_id}")
461
+ Thread.current[key] ||= []
462
+ end
463
+
316
464
  def settings_params(settings = {}, except: [])
317
465
  request_params = @connection_config || {}
318
466
  block_settings = @block_settings || {}
467
+
468
+ case @http_auth
469
+ when HTTP_AUTH_BASIC
470
+ request_params = request_params.except(:user, :password)
471
+ when HTTP_AUTH_X_HEADERS
472
+ request_params = request_params.except(:user, :password, :database)
473
+ end
474
+
319
475
  request_params.merge(block_settings)
320
476
  .merge(settings)
321
477
  .except(*except)
322
478
  .to_param
323
479
  end
324
480
 
481
+ def build_request_headers(include_database: true)
482
+ request_headers = {
483
+ 'Content-Type' => 'application/x-www-form-urlencoded',
484
+ 'User-Agent' => ClickhouseAdapter::USER_AGENT
485
+ }
486
+
487
+ case @http_auth
488
+ when HTTP_AUTH_BASIC
489
+ if @config[:username] && @config[:password]
490
+ credentials = Base64.strict_encode64("#{@config[:username]}:#{@config[:password]}")
491
+ request_headers['Authorization'] = "Basic #{credentials}"
492
+ end
493
+ when HTTP_AUTH_X_HEADERS
494
+ request_headers['X-ClickHouse-User'] = @config[:username].to_s if @config[:username]
495
+ request_headers['X-ClickHouse-Key'] = @config[:password].to_s if @config[:password]
496
+ request_headers['X-ClickHouse-Database'] = @config[:database].to_s if include_database && @config[:database]
497
+ end
498
+
499
+ request_headers
500
+ end
501
+
325
502
  # Returns a hash of table names to their engine types
326
503
  def table_engines(table_names = nil)
327
504
  table_names_sql = if table_names.present?
@@ -54,7 +54,7 @@ module ActiveRecord
54
54
 
55
55
  # @return [String, Hash, Array]
56
56
  def process_successful_response
57
- raise_generic!(@sql) if @body.include?('DB::Exception') && @body.match?(DB_EXCEPTION_REGEXP)
57
+ raise_database_error!(@sql) if @body.include?('DB::Exception') && @body.match?(DB_EXCEPTION_REGEXP)
58
58
 
59
59
  format_body_response
60
60
  end
@@ -103,14 +103,17 @@ module ActiveRecord
103
103
  JSON.parse(payload, decimal_class: BigDecimal)
104
104
  end
105
105
 
106
- def raise_database_error!
106
+ def raise_database_error!(sql = nil)
107
107
  case @body
108
108
  when /DB::Exception:.*\(UNKNOWN_DATABASE\)/
109
109
  raise ActiveRecord::NoDatabaseError
110
110
  when /DB::Exception:.*\(DATABASE_ALREADY_EXISTS\)/
111
111
  raise ActiveRecord::DatabaseAlreadyExists
112
+ when /DB::Exception:.*\(TIMEOUT_EXCEEDED\)/
113
+ # server-side cancellation, vs. ActiveRecord::AdapterTimeout (client gave up)
114
+ raise ActiveRecord::StatementTimeout, "Response code: #{@raw_response.code}:\n#{@body}#{"\nQuery: #{sql}" if sql}"
112
115
  else
113
- raise_generic!
116
+ raise_generic!(sql)
114
117
  end
115
118
  end
116
119
 
@@ -41,7 +41,7 @@ module ActiveRecord
41
41
  unsigned = options[:unsigned]
42
42
  unsigned = true if unsigned.nil?
43
43
 
44
- kind = :uint32 # default
44
+ kind = unsigned ? :uint32 : :int32 # default
45
45
 
46
46
  if options[:limit]
47
47
  if unsigned
@@ -63,6 +63,12 @@ module ActiveRecord
63
63
  args.each { |name| column(name, kind, **options.except(:limit, :unsigned)) }
64
64
  end
65
65
 
66
+ def float(*args, **options)
67
+ kind = options[:limit] == 8 ? :float64 : :float
68
+
69
+ args.each { |name| column(name, kind, **options.except(:limit)) }
70
+ end
71
+
66
72
  def datetime(*args, **options)
67
73
  kind = :datetime
68
74