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
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

Constants included from ActiveRecord::ConnectionAdapters::Clickhouse::SchemaStatements

ActiveRecord::ConnectionAdapters::Clickhouse::SchemaStatements::DEFAULT_RESPONSE_FORMAT

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, #migration_context, #schema_migration, #show_create_function, #table_options, #tables, #views, #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.



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 117

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

  @prepared_statements = false

  connect
end

Class Method Details

.extract_limit(sql_type) ⇒ Object

:nodoc:



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 181

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
    else
      super
  end
end

.extract_precision(sql_type) ⇒ Object



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

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



201
202
203
204
205
206
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 201

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:



212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 212

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



403
404
405
406
407
408
409
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 403

def add_column(table_name, column_name, type, **options)
  return if options[:if_not_exists] == true && column_exists?(table_name, column_name, type)

  at = create_alter_table table_name
  at.add_column(column_name, type, **options)
  execute(schema_creation.accept(at), nil, settings: {wait_end_of_query: 1, send_progress_in_http_headers: 1})
end

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

Adds index description to tables metadata



434
435
436
437
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 434

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



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

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:



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

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

#build_insert_sql(insert) ⇒ Object

:nodoc:



513
514
515
516
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 513

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

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



417
418
419
420
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 417

def change_column(table_name, column_name, type, **options)
  result = do_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



428
429
430
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 428

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



422
423
424
425
426
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 422

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



456
457
458
459
460
461
462
463
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 456

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



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

def cluster
  @config[:cluster_name]
end

#column_name_for_operation(operation, node) ⇒ Object

:nodoc:



274
275
276
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 274

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

#create_database(name) ⇒ Object

Create a new ClickHouse database.



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

def create_database(name)
  sql = apply_cluster "CREATE DATABASE #{quote_table_name(name)}"
  log_with_debug(sql, adapter_name) do
    res = @connection.post("/?#{@connection_config.except(:database).to_param}", sql)
    process_response(res, DEFAULT_RESPONSE_FORMAT)
  end
end

#create_function(name, body) ⇒ Object



354
355
356
357
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 354

def create_function(name, body)
  fd = "CREATE FUNCTION #{apply_cluster(quote_table_name(name))} AS #{body}"
  do_execute(fd, format: nil)
end

#create_savepoint(name) ⇒ Object

Savepoints are not supported, noop



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

def create_savepoint(name)
end

#create_schema_dumper(options) ⇒ Object

:nodoc:



295
296
297
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 295

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

#create_table(table_name, **options, &block) ⇒ Object



327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 327

def create_table(table_name, **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

  do_execute(schema_creation.accept(td), format: nil)

  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, **options) {|td| ... } ⇒ Object

Yields:

  • (td)


314
315
316
317
318
319
320
321
322
323
324
325
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 314

def create_view(table_name, **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

  do_execute(schema_creation.accept(td), format: nil)
end

#databaseObject



473
474
475
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 473

def database
  @config[:database]
end

#database_engine_atomic?Boolean

Returns:

  • (Boolean)


489
490
491
492
493
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 489

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.



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

def drop_database(name) #:nodoc:
  sql = apply_cluster "DROP DATABASE IF EXISTS #{quote_table_name(name)}"
  log_with_debug(sql, adapter_name) do
    res = @connection.post("/?#{@connection_config.except(:database).to_param}", sql)
    process_response(res, DEFAULT_RESPONSE_FORMAT)
  end
end

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



393
394
395
396
397
398
399
400
401
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 393

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]

  do_execute(query, format: nil)
end

#drop_functionsObject



368
369
370
371
372
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 368

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

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

:nodoc:



378
379
380
381
382
383
384
385
386
387
388
389
390
391
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 378

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]

  do_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



154
155
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 154

def exec_rollback_to_savepoint(name)
end

#migrations_pathsObject



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

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

#native_database_typesObject

:nodoc:



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

def native_database_types #:nodoc:
  NATIVE_DATABASE_TYPES
end

#primary_keys(table_name) ⇒ Object

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



284
285
286
287
288
289
290
291
292
293
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 284

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



250
251
252
253
254
255
256
257
258
259
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 250

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



262
263
264
265
266
267
268
269
270
271
272
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 262

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



446
447
448
449
450
451
452
453
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 446

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



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

def release_savepoint(name)
end

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



411
412
413
414
415
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 411

def remove_column(table_name, column_name, type = nil, **options)
  return if options[:if_exists] == true && !column_exists?(table_name, column_name)

  execute("ALTER TABLE #{quote_table_name(table_name)} #{remove_column_for_alter(table_name, column_name, type, **options)}", nil, settings: {wait_end_of_query: 1, send_progress_in_http_headers: 1})
end

#remove_index(table_name, name) ⇒ Object

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



440
441
442
443
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 440

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



374
375
376
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 374

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

#replicaObject



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

def replica
  @config[:replica_name]
end

#replica_path(table) ⇒ Object



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

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

#server_versionObject

Return ClickHouse server version



146
147
148
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 146

def server_version
  @server_version ||= do_system_execute('SELECT version()')['data'][0][0]
end

#show_create_table(table) ⇒ String

Parameters:

  • table (String)

Returns:

  • (String)


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

def show_create_table(table)
  do_system_execute("SHOW CREATE TABLE `#{table}`")['data'].try(:first).try(:first).gsub(/[\n\s]+/m, ' ').gsub("#{@config[:database]}.", "")
end

#supports_indexes_in_create?Boolean

Returns:

  • (Boolean)


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

def supports_indexes_in_create?
  true
end

#supports_insert_on_duplicate_skip?Boolean

Returns:

  • (Boolean)


505
506
507
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 505

def supports_insert_on_duplicate_skip?
  true
end

#supports_insert_on_duplicate_update?Boolean

Returns:

  • (Boolean)


509
510
511
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 509

def supports_insert_on_duplicate_update?
  true
end

#type_mapObject

In Rails 7 used constant TYPE_MAP, we need redefine method



246
247
248
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 246

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)


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

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

#use_replica?Boolean

Returns:

  • (Boolean)


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

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

#valid_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


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

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