Class: ActiveRecord::ConnectionAdapters::ClickhouseAdapter

Inherits:
AbstractAdapter
  • Object
show all
Includes:
ActiveRecord::ConnectionAdapters::Clickhouse::Quoting, ActiveRecord::ConnectionAdapters::Clickhouse::SchemaStatements
Defined in:
lib/active_record/connection_adapters/clickhouse_adapter.rb

Constant Summary collapse

ADAPTER_NAME =
'Clickhouse'.freeze
DEFAULT_RESPONSE_FORMAT =
'JSONCompactEachRowWithNamesAndTypes'.freeze
USER_AGENT =
"ClickHouse ActiveRecord #{ClickhouseActiverecord::VERSION}"
NATIVE_DATABASE_TYPES =
{
  string: { name: 'String' },
  integer: { name: 'UInt32' },
  big_integer: { name: 'UInt64' },
  float: { name: 'Float32' },
  decimal: { name: 'Decimal' },
  datetime: { name: 'DateTime' },
  datetime64: { name: 'DateTime64' },
  date: { name: 'Date' },
  boolean: { name: 'Bool' },
  uuid: { name: 'UUID' },

  enum8: { name: 'Enum8' },
  enum16: { name: 'Enum16' },

  int8:  { name: 'Int8' },
  int16: { name: 'Int16' },
  int32: { name: 'Int32' },
  int64:  { name: 'Int64' },
  int128: { name: 'Int128' },
  int256: { name: 'Int256' },

  uint8: { name: 'UInt8' },
  uint16: { name: 'UInt16' },
  uint32: { name: 'UInt32' },
  uint64: { name: 'UInt64' },
  # uint128: { name: 'UInt128' }, not yet implemented in clickhouse
  uint256: { name: 'UInt256' },
}.freeze

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ActiveRecord::ConnectionAdapters::Clickhouse::SchemaStatements

#add_index_options, #assume_migrated_upto_version, #data_sources, #do_execute, #do_system_execute, #exec_delete, #exec_insert, #exec_insert_all, #exec_update, #execute, #functions, #indexes, #internal_exec_query, #internal_metadata, #materialized_views, #migration_context, #schema_migration, #show_create_function, #table_options, #tables, #views, #with_response_format, #with_settings, #with_yaml_fallback

Constructor Details

#initialize(config_or_deprecated_connection, deprecated_logger = nil, deprecated_connection_options = nil, deprecated_config = nil) ⇒ ClickhouseAdapter

Initializes and connects a Clickhouse adapter.



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 121

def initialize(config_or_deprecated_connection, deprecated_logger = nil, deprecated_connection_options = nil, deprecated_config = nil)
  super
  if @config[:connection]
    connection = {
      connection: @config[:connection]
    }
  else
    port = @config[:port] || 8123
    connection = {
      host: @config[:host] || 'localhost',
      port: port,
      ssl: @config[:ssl].present? ? @config[:ssl] : port == 443,
      sslca: @config[:sslca],
      read_timeout: @config[:read_timeout],
      write_timeout: @config[:write_timeout],
      keep_alive_timeout: @config[:keep_alive_timeout]
    }
  end
  @connection_parameters = connection

  @connection_config = { user: @config[:username], password: @config[:password], database: @config[:database] }.compact
  @debug = @config[:debug] || false
  @response_format = @config[:format] || DEFAULT_RESPONSE_FORMAT

  @prepared_statements = false

  connect
end

Class Method Details

.extract_limit(sql_type) ⇒ Object

:nodoc:



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 186

def extract_limit(sql_type) # :nodoc:
  case sql_type
    when /(Nullable)?\(?String\)?/
      super('String')
    when /(Nullable)?\(?U?Int8\)?/
      1
    when /(Nullable)?\(?U?Int16\)?/
      2
    when /(Nullable)?\(?U?Int32\)?/
      nil
    when /(Nullable)?\(?U?Int64\)?/
      8
    when /(Nullable)?\(?U?Int128\)?/
      16
    else
      super
  end
end

.extract_precision(sql_type) ⇒ Object



215
216
217
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 215

def extract_precision(sql_type)
  $1.to_i if sql_type =~ /\((\d+)(,\s?\d+)?\)/
end

.extract_scale(sql_type) ⇒ Object

‘extract_scale` and `extract_precision` are the same as in the Rails abstract base class, except this permits a space after the comma



208
209
210
211
212
213
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 208

def extract_scale(sql_type)
  case sql_type
  when /\((\d+)\)/ then 0
  when /\((\d+)(,\s?(\d+))\)/ then $3.to_i
  end
end

.initialize_type_map(m) ⇒ Object

:nodoc:



219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 219

def initialize_type_map(m) # :nodoc:
  super
  register_class_with_limit m, %r(String), Type::String
  register_class_with_limit m, 'Date',  Clickhouse::OID::Date
  register_class_with_precision m, %r(datetime)i,  Clickhouse::OID::DateTime

  register_class_with_limit m, %r(Int8), Type::Integer
  register_class_with_limit m, %r(Int16), Type::Integer
  register_class_with_limit m, %r(Int32), Type::Integer
  register_class_with_limit m, %r(Int64), Type::Integer
  register_class_with_limit m, %r(Int128), Type::Integer
  register_class_with_limit m, %r(Int256), Type::Integer

  register_class_with_limit m, %r(UInt8), Type::UnsignedInteger
  register_class_with_limit m, %r(UInt16), Type::UnsignedInteger
  register_class_with_limit m, %r(UInt32), Type::UnsignedInteger
  register_class_with_limit m, %r(UInt64), Type::UnsignedInteger
  #register_class_with_limit m, %r(UInt128), Type::UnsignedInteger #not implemnted in clickhouse
  register_class_with_limit m, %r(UInt256), Type::UnsignedInteger

  m.register_type %r(bool)i, ActiveModel::Type::Boolean.new
  m.register_type %r{uuid}i, Clickhouse::OID::Uuid.new
  # register_class_with_limit m, %r(Array), Clickhouse::OID::Array
  m.register_type(%r(Array)) do |sql_type|
    Clickhouse::OID::Array.new(sql_type)
  end

  m.register_type(%r(Map)) do |sql_type|
    Clickhouse::OID::Map.new(sql_type)
  end
end

Instance Method Details

#add_column(table_name, column_name, type, **options) ⇒ Object



406
407
408
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 406

def add_column(table_name, column_name, type, **options)
  with_settings(wait_end_of_query: 1, send_progress_in_http_headers: 1) { super }
end

#add_index(table_name, expression, **options) ⇒ Object

Adds index description to tables metadata



431
432
433
434
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 431

def add_index(table_name, expression, **options)
  index = add_index_options(apply_cluster(table_name), expression, **options)
  execute schema_creation.accept(CreateIndexDefinition.new(index))
end

#apply_cluster(sql) ⇒ Object



508
509
510
511
512
513
514
515
516
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 508

def apply_cluster(sql)
  if cluster
    normalized_cluster_name = cluster.start_with?('{') ? "'#{cluster}'" : cluster

    "#{sql} ON CLUSTER #{normalized_cluster_name}"
  else
    sql
  end
end

#arel_visitorObject

:nodoc:



169
170
171
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 169

def arel_visitor # :nodoc:
  Arel::Visitors::Clickhouse.new(self)
end

#build_insert_sql(insert) ⇒ Object

:nodoc:



526
527
528
529
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 526

def build_insert_sql(insert) # :nodoc:
  sql = +"INSERT #{insert.into} #{insert.values_list}"
  sql
end

#change_column(table_name, column_name, type, **options) ⇒ Object



414
415
416
417
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 414

def change_column(table_name, column_name, type, **options)
  result = execute("ALTER TABLE #{quote_table_name(table_name)} #{change_column_for_alter(table_name, column_name, type, **options)}", nil, settings: {wait_end_of_query: 1, send_progress_in_http_headers: 1})
  raise "Error parse json response: #{result}" if result.presence && !result.is_a?(Hash)
end

#change_column_default(table_name, column_name, default) ⇒ Object



425
426
427
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 425

def change_column_default(table_name, column_name, default)
  change_column table_name, column_name, nil, {default: default}.compact
end

#change_column_null(table_name, column_name, null, default = nil) ⇒ Object



419
420
421
422
423
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 419

def change_column_null(table_name, column_name, null, default = nil)
  structure = table_structure(table_name).select{|v| v[0] == column_name.to_s}.first
  raise "Column #{column_name} not found in table #{table_name}" if structure.nil?
  change_column table_name, column_name, structure[1].gsub(/(Nullable\()?(.*?)\)?/, '\2'), {null: null, default: default}.compact
end

#clear_index(table_name, name, if_exists: false, partition: nil) ⇒ Object

Deletes the secondary index files from disk without removing description



453
454
455
456
457
458
459
460
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 453

def clear_index(table_name, name, if_exists: false, partition: nil)
  query = [apply_cluster("ALTER TABLE #{quote_table_name(table_name)}")]
  query << 'CLEAR INDEX'
  query << 'IF EXISTS' if if_exists
  query << quote_column_name(name)
  query << "IN PARTITION #{quote_column_name(partition)}" if partition
  execute query.join(' ')
end

#clusterObject



462
463
464
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 462

def cluster
  @config[:cluster_name]
end

#column_name_for_operation(operation, node) ⇒ Object

:nodoc:



281
282
283
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 281

def column_name_for_operation(operation, node) # :nodoc:
  visitor.compile(node)
end

#create_database(name) ⇒ Object

Create a new ClickHouse database.



315
316
317
318
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 315

def create_database(name)
  sql = apply_cluster "CREATE DATABASE #{quote_table_name(name)}"
  do_system_execute sql, adapter_name, except_params: [:database]
end

#create_function(name, body, **options) ⇒ Object



360
361
362
363
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 360

def create_function(name, body, **options)
  fd = "CREATE#{' OR REPLACE' if options[:force]} FUNCTION #{apply_cluster(quote_table_name(name))} AS #{body}"
  execute(fd)
end

#create_savepoint(name) ⇒ Object

Savepoints are not supported, noop



156
157
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 156

def create_savepoint(name)
end

#create_schema_dumper(options) ⇒ Object

:nodoc:



302
303
304
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 302

def create_schema_dumper(options) # :nodoc:
  ClickhouseActiverecord::SchemaDumper.create(self, options)
end

#create_table(table_name, request_settings: {}, **options, &block) ⇒ Object



333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 333

def create_table(table_name, request_settings: {}, **options, &block)
  options = apply_replica(table_name, options)
  td = create_table_definition(apply_cluster(table_name), **options)
  block.call td if block_given?
  # support old migration version: in 5.0 options id: :integer, but 7.1 options empty
  # todo remove auto add id column in future
  if (!options.key?(:id) || options[:id].present? && options[:id] != false) && td[:id].blank? && options[:as].blank?
    td.column(:id, options[:id] || :integer, null: false)
  end

  if options[:force]
    drop_table(table_name, options.merge(if_exists: true))
  end

  execute(schema_creation.accept(td), settings: request_settings)

  if options[:with_distributed]
    distributed_table_name = options.delete(:with_distributed)
    sharding_key = options.delete(:sharding_key) || 'rand()'
    raise 'Set a cluster' unless cluster

    distributed_options =
      "Distributed(#{cluster}, #{@connection_config[:database]}, #{table_name}, #{sharding_key})"
    create_table(distributed_table_name, **options.merge(options: distributed_options), &block)
  end
end

#create_view(table_name, request_settings: {}, **options) {|td| ... } ⇒ Object

Yields:

  • (td)


320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 320

def create_view(table_name, request_settings: {}, **options)
  options.merge!(view: true)
  options = apply_replica(table_name, options)
  td = create_table_definition(apply_cluster(table_name), **options)
  yield td if block_given?

  if options[:force]
    drop_table(table_name, options.merge(if_exists: true))
  end

  execute(schema_creation.accept(td), settings: request_settings)
end

#databaseObject



470
471
472
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 470

def database
  @config[:database]
end

#database_engine_atomic?Boolean

Returns:

  • (Boolean)


502
503
504
505
506
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 502

def database_engine_atomic?
  current_database_engine = "select engine from system.databases where name = '#{@connection_config[:database]}'"
  res = select_one(current_database_engine)
  res['engine'] == 'Atomic' if res
end

#drop_database(name) ⇒ Object

Drops a ClickHouse database.



366
367
368
369
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 366

def drop_database(name) #:nodoc:
  sql = apply_cluster "DROP DATABASE IF EXISTS #{quote_table_name(name)}"
  do_system_execute sql, adapter_name, except_params: [:database]
end

#drop_function(name, options = {}) ⇒ Object



396
397
398
399
400
401
402
403
404
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 396

def drop_function(name, options = {})
  query = "DROP FUNCTION"
  query = "#{query} IF EXISTS " if options[:if_exists]
  query = "#{query} #{quote_table_name(name)}"
  query = apply_cluster(query)
  query = "#{query} SYNC" if options[:sync]

  execute(query)
end

#drop_functionsObject



371
372
373
374
375
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 371

def drop_functions
  functions.each do |function|
    drop_function(function)
  end
end

#drop_table(table_name, options = {}) ⇒ Object

:nodoc:



381
382
383
384
385
386
387
388
389
390
391
392
393
394
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 381

def drop_table(table_name, options = {}) # :nodoc:
  query = "DROP TABLE"
  query = "#{query} IF EXISTS " if options[:if_exists]
  query = "#{query} #{quote_table_name(table_name)}"
  query = apply_cluster(query)
  query = "#{query} SYNC" if options[:sync]

  execute(query)

  if options[:with_distributed]
    distributed_table_name = options.delete(:with_distributed)
    drop_table(distributed_table_name, **options)
  end
end

#exec_rollback_to_savepoint(name) ⇒ Object



159
160
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 159

def exec_rollback_to_savepoint(name)
end

#migrations_pathsObject



165
166
167
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 165

def migrations_paths
  @config[:migrations_paths] || 'db/migrate_clickhouse'
end

#native_database_typesObject

:nodoc:



173
174
175
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 173

def native_database_types #:nodoc:
  NATIVE_DATABASE_TYPES
end

#primary_keys(table_name) ⇒ Object

SCHEMA STATEMENTS ========================================



291
292
293
294
295
296
297
298
299
300
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 291

def primary_keys(table_name)
  if server_version.to_f >= 23.4
    structure = do_system_execute("SHOW COLUMNS FROM `#{table_name}`")
    return structure['data'].select {|m| m[3]&.include?('PRI') }.pluck(0)
  end

  pk = table_structure(table_name).first
  return ['id'] if pk.present? && pk[0] == 'id'
  []
end

#quote(value) ⇒ Object



257
258
259
260
261
262
263
264
265
266
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 257

def quote(value)
  case value
  when Array
    '[' + value.map { |v| quote(v) }.join(', ') + ']'
  when Hash
    '{' + value.map { |k, v| "#{quote(k)}: #{quote(v)}" }.join(', ') + '}'
  else
    super
  end
end

#quoted_date(value) ⇒ Object

Quoting time without microseconds



269
270
271
272
273
274
275
276
277
278
279
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 269

def quoted_date(value)
  if value.acts_like?(:time)
    zone_conversion_method = ActiveRecord.default_timezone == :utc ? :getutc : :getlocal

    if value.respond_to?(zone_conversion_method)
      value = value.send(zone_conversion_method)
    end
  end

  value.to_fs(:db)
end

#rebuild_index(table_name, name, if_exists: false, partition: nil) ⇒ Object

Rebuilds the secondary index name for the specified partition_name



443
444
445
446
447
448
449
450
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 443

def rebuild_index(table_name, name, if_exists: false, partition: nil)
  query = [apply_cluster("ALTER TABLE #{quote_table_name(table_name)}")]
  query << 'MATERIALIZE INDEX'
  query << 'IF EXISTS' if if_exists
  query << quote_column_name(name)
  query << "IN PARTITION #{quote_column_name(partition)}" if partition
  execute query.join(' ')
end

#release_savepoint(name) ⇒ Object



162
163
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 162

def release_savepoint(name)
end

#remove_column(table_name, column_name, type = nil, **options) ⇒ Object



410
411
412
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 410

def remove_column(table_name, column_name, type = nil, **options)
  with_settings(wait_end_of_query: 1, send_progress_in_http_headers: 1) { super }
end

#remove_index(table_name, name) ⇒ Object

Removes index description from tables metadata and deletes index files from disk



437
438
439
440
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 437

def remove_index(table_name, name)
  query = apply_cluster("ALTER TABLE #{quote_table_name(table_name)}")
  execute "#{query} DROP INDEX #{quote_column_name(name)}"
end

#rename_table(table_name, new_name) ⇒ Object



377
378
379
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 377

def rename_table(table_name, new_name)
  execute apply_cluster "RENAME TABLE #{quote_table_name(table_name)} TO #{quote_table_name(new_name)}"
end

#replicaObject



466
467
468
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 466

def replica
  @config[:replica_name]
end

#replica_path(table) ⇒ Object

Returns the path for replication metadata. When sharding is enabled (shard_name is set), the path includes the shard identifier to ensure unique paths for each shard’s replication metadata. Format with sharding: /clickhouse/tables/#cluster/#shard/#database.table Format without sharding: /clickhouse/tables/#cluster/#database.table



494
495
496
497
498
499
500
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 494

def replica_path(table)
  if shard
    "/clickhouse/tables/#{cluster}/#{shard}/#{@connection_config[:database]}.#{table}"
  else
    "/clickhouse/tables/#{cluster}/#{@connection_config[:database]}.#{table}"
  end
end

#server_versionObject

Return ClickHouse server version



151
152
153
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 151

def server_version
  @server_version ||= select_value('SELECT version()')
end

#shardObject

Returns the shard name from the configuration. This is used to identify the shard in replication paths when using both sharding and replication. Required when you have multiple shards with replication to ensure unique paths for each shard’s replication metadata.



477
478
479
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 477

def shard
  @config[:shard_name]
end

#show_create_table(table, single_line: true) ⇒ String

Parameters:

  • table (String)
  • [Boolean] (Hash)

    a customizable set of options

Returns:

  • (String)


309
310
311
312
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 309

def show_create_table(table, single_line: true)
  sql = do_system_execute("SHOW CREATE TABLE `#{table}`")['data'].try(:first).try(:first).gsub("#{@config[:database]}.", '')
  single_line ? sql.squish : sql
end

#supports_indexes_in_create?Boolean

Returns:

  • (Boolean)


181
182
183
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 181

def supports_indexes_in_create?
  true
end

#supports_insert_on_duplicate_skip?Boolean

Returns:

  • (Boolean)


518
519
520
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 518

def supports_insert_on_duplicate_skip?
  true
end

#supports_insert_on_duplicate_update?Boolean

Returns:

  • (Boolean)


522
523
524
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 522

def supports_insert_on_duplicate_update?
  true
end

#type_mapObject

In Rails 7 used constant TYPE_MAP, we need redefine method



253
254
255
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 253

def type_map
  @type_map ||= Type::TypeMap.new.tap { |m| ClickhouseAdapter.initialize_type_map(m) }
end

#use_default_replicated_merge_tree_params?Boolean

Returns:

  • (Boolean)


481
482
483
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 481

def use_default_replicated_merge_tree_params?
  database_engine_atomic? && @config[:use_default_replicated_merge_tree_params]
end

#use_replica?Boolean

Returns:

  • (Boolean)


485
486
487
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 485

def use_replica?
  (replica || use_default_replicated_merge_tree_params?) && cluster
end

#valid_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


177
178
179
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 177

def valid_type?(type)
  !native_database_types[type].nil?
end