blob: 410a7ec86bce08d9429b2edf1b8d4c52bfe0d82a (
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
# frozen_string_literal: true
module ClickHouse
class Migration
cattr_accessor :verbose, :client_configuration
attr_accessor :name, :version
class << self
attr_accessor :delegate
end
def initialize(name = self.class.name, version = nil)
@name = name
@version = version
end
self.client_configuration = ClickHouse::Client.configuration
self.verbose = true
# instantiate the delegate object after initialize is defined
self.delegate = new
MIGRATION_FILENAME_REGEXP = /\A([0-9]+)_([_a-z0-9]*)\.?([_a-z0-9]*)?\.rb\z/
def database
self.class.constants.include?(:SCHEMA) ? self.class.const_get(:SCHEMA, false) : :main
end
def execute(query)
ClickHouse::Client.execute(query, database, self.class.client_configuration)
end
def up
self.class.delegate = self
return unless self.class.respond_to?(:up)
self.class.up
end
def down
self.class.delegate = self
return unless self.class.respond_to?(:down)
self.class.down
end
# Execute this migration in the named direction
def migrate(direction)
return unless respond_to?(direction)
case direction
when :up then announce 'migrating'
when :down then announce 'reverting'
end
time = Benchmark.measure do
exec_migration(direction)
end
case direction
when :up then announce format("migrated (%.4fs)", time.real)
write
when :down then announce format("reverted (%.4fs)", time.real)
write
end
end
private
def exec_migration(direction)
# noinspection RubyCaseWithoutElseBlockInspection
case direction
when :up then up
when :down then down
end
end
def write(text = '')
$stdout.puts(text) if verbose
end
def announce(message)
text = "#{version} #{name}: #{message}"
length = [0, 75 - text.length].max
write format('== %s %s', text, '=' * length)
end
end
end
|