Class: ClickhouseActiverecord::Tasks

Inherits:
Object
  • Object
show all
Defined in:
lib/clickhouse-activerecord/tasks.rb

Instance Method Summary collapse

Constructor Details

#initialize(configuration) ⇒ Tasks

Returns a new instance of Tasks.



7
8
9
# File 'lib/clickhouse-activerecord/tasks.rb', line 7

def initialize(configuration)
  @configuration = configuration.with_indifferent_access
end

Instance Method Details

#createObject



11
12
13
14
15
16
17
18
19
20
# File 'lib/clickhouse-activerecord/tasks.rb', line 11

def create
  establish_master_connection
  connection.create_database @configuration['database']
rescue ActiveRecord::StatementInvalid => e
  if e.cause.to_s.include?('already exists')
    raise ActiveRecord::DatabaseAlreadyExists
  else
    raise
  end
end

#dropObject



22
23
24
25
# File 'lib/clickhouse-activerecord/tasks.rb', line 22

def drop
  establish_master_connection
  connection.drop_database @configuration['database']
end

#migrateObject



56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/clickhouse-activerecord/tasks.rb', line 56

def migrate
  check_target_version

  verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] != "false" : true
  scope = ENV["SCOPE"]
  verbose_was, ActiveRecord::Migration.verbose = ActiveRecord::Migration.verbose, verbose
  connection.migration_context.migrate(target_version) do |migration|
    scope.blank? || scope == migration.scope
  end
  ActiveRecord::Base.clear_cache!
ensure
  ActiveRecord::Migration.verbose = verbose_was
end

#purgeObject



27
28
29
30
31
# File 'lib/clickhouse-activerecord/tasks.rb', line 27

def purge
  ActiveRecord::Base.connection_handler.clear_active_connections!(:all)
  drop
  create
end

#structure_dump(*args) ⇒ Object



33
34
35
36
37
38
39
40
41
42
# File 'lib/clickhouse-activerecord/tasks.rb', line 33

def structure_dump(*args)
  tables = connection.execute("SHOW TABLES FROM #{@configuration['database']}")['data'].flatten

  File.open(args.first, 'w:utf-8') do |file|
    tables.each do |table|
      next if table.match(/\.inner/)
      file.puts connection.execute("SHOW CREATE TABLE #{table}")['data'].try(:first).try(:first).gsub("#{@configuration['database']}.", '') + ";\n\n"
    end
  end
end

#structure_load(*args) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/clickhouse-activerecord/tasks.rb', line 44

def structure_load(*args)
  File.read(args.first).split(";\n\n").each do |sql|
    if sql.gsub(/[a-z]/i, '').blank?
      next
    elsif sql =~ /^INSERT INTO/
      connection.do_execute(sql, nil, format: nil)
    else
      connection.execute(sql)
    end
  end
end