Module: CoreExtensions::ActiveRecord::SchemaMigration

Defined in:
lib/core_extensions/active_record/schema_migration.rb

Instance Method Summary collapse

Instance Method Details

#connectionObject



51
52
53
54
55
56
57
# File 'lib/core_extensions/active_record/schema_migration.rb', line 51

def connection
  if ::ActiveRecord::version >= Gem::Version.new('7.2')
    @pool.lease_connection
  else
    super
  end
end

#create_tableObject



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
# File 'lib/core_extensions/active_record/schema_migration.rb', line 5

def create_table
  return super unless connection.is_a?(::ActiveRecord::ConnectionAdapters::ClickhouseAdapter)

  return if table_exists?

  version_options = connection.internal_string_options_for_primary_key
  table_options = {
    id: false, options: 'ReplacingMergeTree(ver) ORDER BY (version)', if_not_exists: true
  }
  full_config = connection.instance_variable_get(:@config) || {}

  if full_config[:distributed_service_tables]
    table_options.merge!(with_distributed: table_name, sharding_key: 'cityHash64(version)')

    distributed_suffix = "_#{full_config[:distributed_service_tables_suffix] || 'distributed'}"
  else
    distributed_suffix = ''
  end

  connection.create_table(table_name + distributed_suffix.to_s, **table_options) do |t|
    t.string :version, **version_options
    t.column :active, 'Int8', null: false, default: '1'
    t.datetime :ver, null: false, default: -> { 'now()' }
  end
end

#delete_version(version) ⇒ Object



31
32
33
34
35
36
37
# File 'lib/core_extensions/active_record/schema_migration.rb', line 31

def delete_version(version)
  return super unless connection.is_a?(::ActiveRecord::ConnectionAdapters::ClickhouseAdapter)

  im = ::Arel::InsertManager.new(arel_table)
  im.insert(arel_table[primary_key] => version.to_s, arel_table['active'] => 0)
  connection.insert(im, "#{self.class} Create Rollback Version", primary_key, version)
end

#versionsObject



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/core_extensions/active_record/schema_migration.rb', line 39

def versions
  return super unless connection.is_a?(::ActiveRecord::ConnectionAdapters::ClickhouseAdapter)

  sm = ::Arel::SelectManager.new(arel_table)
  sm.final!
  sm.project(arel_table[primary_key])
  sm.order(arel_table[primary_key].asc)
  sm.where([arel_table['active'].eq(1)])

  connection.select_values(sm, "#{self.class} Load")
end