Module: Izolenta::ActiveRecordMigration::Helpers

Defined in:
lib/izolenta/active_record_migration.rb

Overview

helpers na

Class Method Summary collapse

Class Method Details

.create_helper_table(helper_table, column_name, column_type) ⇒ Object



30
31
32
# File 'lib/izolenta/active_record_migration.rb', line 30

def create_helper_table(helper_table, column_name, column_type)
  ActiveRecord::Base.connection.execute("CREATE TABLE #{helper_table} ( #{column_name} #{column_type} );")
end

.create_sync_trigger(table, column_name, helper_table_name, options) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/izolenta/active_record_migration.rb', line 34

def create_sync_trigger(table, column_name, helper_table_name, options)
  trg_name = "#{table}_#{column_name}_trg"
  insert_value = if options[:wrapper_function]
    "#{options[:wrapper_function]}(NEW.#{column_name})"
  else
    "NEW.#{column_name}"
  end

  trigger_condition = "WHEN( #{options[:trigger_condition]} )" if options[:trigger_condition]

  ActiveRecord::Base.connection.execute("    CREATE OR REPLACE FUNCTION \#{trg_name}() RETURNS trigger AS $$\n    BEGIN\#{\" \"}\n      INSERT INTO \#{helper_table_name} VALUES ( \#{insert_value} );\n      RETURN NEW;\n    END $$ LANGUAGE plpgSQL;\n\n    CREATE TRIGGER \#{trg_name} BEFORE INSERT ON \#{table}\#{\" \"}\n    FOR EACH ROW\n    \#{trigger_condition}\n    EXECUTE FUNCTION \#{trg_name}();\n  SYNC_TRIGGER\nend\n")

.drop_sync_trigger(table, column_name) ⇒ Object



58
59
60
61
62
63
64
# File 'lib/izolenta/active_record_migration.rb', line 58

def drop_sync_trigger(table, column_name)
  trg_name = "#{table}_#{column_name}_trg"

  ActiveRecord::Base.connection.execute("    DROP TRIGGER IF EXISTS \#{trg_name} ON \#{table};\n  SYNC_TRIGGER\nend\n")

.get_column_type(origin_table, column) ⇒ Object



70
71
72
# File 'lib/izolenta/active_record_migration.rb', line 70

def get_column_type(origin_table, column)
  ActiveRecord::Base.connection.schema_cache.columns_hash(origin_table.to_s)[column.to_s]&.sql_type
end

.get_function_type(wrapper_function) ⇒ Object



74
75
76
77
78
79
# File 'lib/izolenta/active_record_migration.rb', line 74

def get_function_type(wrapper_function)
  ActiveRecord::Base
    .connection
    .execute("SELECT typname FROM pg_type WHERE oid=(SELECT prorettype FROM pg_proc WHERE proname ='#{wrapper_function}')") # rubocop:disable Layout/LineLength
    .first["typname"]
end

.get_new_column_type(origin_table, column, wrapper_function: nil) ⇒ Object



66
67
68
# File 'lib/izolenta/active_record_migration.rb', line 66

def get_new_column_type(origin_table, column, wrapper_function: nil, **)
  wrapper_function ? get_function_type(wrapper_function) : get_column_type(origin_table, column)
end