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::DB_EXCEPTION_REGEXP, 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, #materialized_views, #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.



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
144
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 118

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:



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

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



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

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



204
205
206
207
208
209
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 204

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:



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
243
244
245
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 215

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



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

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



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

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



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

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:



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

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

#build_insert_sql(insert) ⇒ Object

:nodoc:



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

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

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



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

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



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

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



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

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



461
462
463
464
465
466
467
468
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 461

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



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

def cluster
  @config[:cluster_name]
end

#column_name_for_operation(operation, node) ⇒ Object

:nodoc:



277
278
279
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 277

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

#create_database(name) ⇒ Object

Create a new ClickHouse database.



311
312
313
314
315
316
317
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 311

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, **options) ⇒ Object



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

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

#create_savepoint(name) ⇒ Object

Savepoints are not supported, noop



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

def create_savepoint(name)
end

#create_schema_dumper(options) ⇒ Object

:nodoc:



298
299
300
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 298

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

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



332
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
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 332

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

  do_execute(schema_creation.accept(td), format: nil, 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)


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

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

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

#databaseObject



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

def database
  @config[:database]
end

#database_engine_atomic?Boolean

Returns:

  • (Boolean)


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

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.



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

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



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

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



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

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

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

:nodoc:



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

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



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

def exec_rollback_to_savepoint(name)
end

#migrations_pathsObject



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

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

#native_database_typesObject

:nodoc:



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

def native_database_types #:nodoc:
  NATIVE_DATABASE_TYPES
end

#primary_keys(table_name) ⇒ Object

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



287
288
289
290
291
292
293
294
295
296
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 287

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



253
254
255
256
257
258
259
260
261
262
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 253

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



265
266
267
268
269
270
271
272
273
274
275
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 265

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



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

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



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

def release_savepoint(name)
end

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



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

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



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

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



379
380
381
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 379

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



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

def replica
  @config[:replica_name]
end

#replica_path(table) ⇒ Object



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

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

#server_versionObject

Return ClickHouse server version



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

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

#show_create_table(table, single_line: true) ⇒ String

Parameters:

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

    a customizable set of options

Returns:

  • (String)


305
306
307
308
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 305

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)


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

def supports_indexes_in_create?
  true
end

#supports_insert_on_duplicate_skip?Boolean

Returns:

  • (Boolean)


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

def supports_insert_on_duplicate_skip?
  true
end

#supports_insert_on_duplicate_update?Boolean

Returns:

  • (Boolean)


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

def supports_insert_on_duplicate_update?
  true
end

#type_mapObject

In Rails 7 used constant TYPE_MAP, we need redefine method



249
250
251
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 249

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)


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

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

#use_replica?Boolean

Returns:

  • (Boolean)


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

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

#valid_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


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

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