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



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

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



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

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



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

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:



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

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

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



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

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



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

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



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

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



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

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



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

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.



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

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



357
358
359
360
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 357

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



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

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)


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

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



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

def database
  @config[:database]
end

#database_engine_atomic?Boolean

Returns:

  • (Boolean)


492
493
494
495
496
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 492

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.



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

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



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]

  do_execute(query, format: nil)
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]

  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



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

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



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

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



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

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)
  do_execute apply_cluster "RENAME TABLE #{quote_table_name(table_name)} TO #{quote_table_name(new_name)}"
end

#replicaObject



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

def replica
  @config[:replica_name]
end

#replica_path(table) ⇒ Object



488
489
490
# File 'lib/active_record/connection_adapters/clickhouse_adapter.rb', line 488

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) ⇒ String

Parameters:

  • table (String)

Returns:

  • (String)


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

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)


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)


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

def supports_insert_on_duplicate_skip?
  true
end

#supports_insert_on_duplicate_update?Boolean

Returns:

  • (Boolean)


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

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)


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

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

#use_replica?Boolean

Returns:

  • (Boolean)


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

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