summaryrefslogtreecommitdiff
path: root/lib/killjoy/tasks/db.rake
blob: 623b49a87f9e90e5352d7439d940a50eae115cfc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
namespace :db do
  require 'active_support/core_ext/string'
  require 'erb'
  require 'fileutils'
  require 'yaml'
  require_relative '../cassandra/database_configuration'

  def configuration
    @configuration ||= Killjoy::Cassandra::DatabaseConfiguration.new
  end

  task :expand_templates do
    Dir["db/migrate/*.cql.erb"].each do |file|
      configuration.expand(File.expand_path(file))
    end
  end

  desc "Create cassandra keyspace"
  task :create do
    host = configuration.hosts.first
    cql = <<-CQL
CREATE KEYSPACE #{configuration.keyspace} WITH REPLICATION = {
  'class' : 'SimpleStrategy',
  'replication_factor': 1
};
    CQL
    sh "cqlsh #{host} -e \"#{cql.gsub(/\n/, '')}\""
  end

  desc 'Run cassandra migrations'
  task :migrate => :expand_templates do
    host = configuration.hosts.first
    Dir["db/migrate/*.cql"].each do |file|
      sh "cqlsh #{host} -f #{File.expand_path(file)}"
    end
  end

  desc "Drop cassandra keyspace"
  task :drop do
    begin
      host = configuration.hosts.first
      cql = "DROP KEYSPACE #{configuration.keyspace};"
      sh "cqlsh #{host} -e '#{cql}'"
    rescue => error
      puts error.message
    end
  end

  desc "Reset cassandra keyspace"
  task :reset => [:drop, :create, :migrate]

  desc 'generate migration'
  task :generate_migration, [:name] do |task, arguments|
    name = arguments[:name]
    migration_time = DateTime.now.strftime("%Y%m%d%H%M%S")
    migration_name = "#{migration_time}_#{name.parameterize}.cql.erb"
    FileUtils.touch("db/migrate/#{migration_name}")
  end
end