Module: Marty::Migrations

Defined in:
lib/marty/migrations.rb

Constant Summary collapse

MCFLY_INDEX_COLUMNS =

created_dt/obsoleted_dt need to be indexed since they appear in almost all queries.

[
  :created_dt,
  :obsoleted_dt,
]

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.generate_sql_migrations(migrations_dir, sql_files_dir) ⇒ Object



190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/marty/migrations.rb', line 190

def self.generate_sql_migrations(migrations_dir, sql_files_dir)
  sd = Rails.root.join(sql_files_dir)
  md = Rails.root.join(migrations_dir)
  sql_files = Dir.glob("#{sd}/**/*.sql")
  mig_files = Dir.glob("#{migrations_dir}/*.rb").map do |f|
    m = /\A.*\/([0-9]+)_v([0-9]+)_sql_(.*)\.rb\z/.match(f)
    { name: m[3],
      timestamp: m[1],
      version: m[2].to_i,
      raw_sql: "#{md}/sql/#{m[1]}_v#{m[2]}_sql_#{m[3]}.sql"
    }
  end.group_by { |a| a[:name] }.each do |_k, v|
    v.sort! { |a, b| b[:version] <=> a[:version] }
  end
  time_now = Time.zone.now.utc
  gen_count = 0

  sql_files.each do |sql|
    base = File.basename(sql, '.sql')
    existing = mig_files[base].first rescue nil
    # must ensure CRLF line endings or SQL Server keep asking about line
    # endings whenever you generating script
    sql_lines = lines_to_crlf(File.open(sql, 'r').readlines)
    next if existing && sql_lines == File.open(existing[:raw_sql]).readlines

    timestamp = (time_now + gen_count.seconds).strftime('%Y%m%d%H%M%S')
    v = existing && existing[:version] + 1 || 1
    klass = "v#{v}_sql_#{base}"
    newbase = "#{timestamp}_#{klass}"
    mig_name = File.join(md, "#{newbase}.rb")
    sql_snap_literal = Rails.root.join(md, 'sql', "#{newbase}.sql")
    sql_snap_call =
      "Rails.root.join('#{migrations_dir}', 'sql', '#{newbase}.sql')"

    File.open(sql_snap_literal, 'w') do |f|
      f.print sql_lines.join
    end
    Rails.logger.info "creating #{newbase}.rb"

    # only split on "GO" at the start of a line with optional whitespace
    # before EOL.  GO in comments could trigger this and will cause an error
    File.open(mig_name, 'w') do |f|
      f.print <<OUT
class #{klass.camelcase} < ActiveRecord::Migration[4.2]

def up
  path = #{sql_snap_call}
  batches = File.read(path).split(/^GO\\s*$/i)
  batches.each { |batch| execute batch }
end

def down
  announce('must rollback manually')
end

end
OUT
    end
    gen_count += 1
  end
end

.lines_to_crlf(lines) ⇒ Object



183
184
185
186
187
188
# File 'lib/marty/migrations.rb', line 183

def self.lines_to_crlf(lines)
  lines.map do |line|
    line.encode(line.encoding, universal_newline: true).
      encode(line.encoding, crlf_newline: true)
  end
end

.write_view(target_dir, target_view, klass, jsons, excludes, extras) ⇒ Object



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/marty/migrations.rb', line 124

def self.write_view(target_dir, target_view, klass, jsons, excludes, extras)
  colnames = klass.columns_hash.keys
  excludes += ['user_id', 'o_user_id']
  joins = ['join marty_users u on main.user_id = u.id',
           'left join marty_users ou on main.o_user_id = ou.id']
  columns = ['u.login AS user_name',
             'ou.login AS obsoleted_user']
  jointabs = {}
  colnames.each do |c|
    if jsons[c]
      jsons[c].each do |subc|
        if subc.class == Array
          subcol, type, fn = subc
          columns.push "#{fn || ''}(main.#{c} ->> '#{subcol}')::#{type} " +
                       "as \"#{c}_#{subcol}\""
        else
          columns.push "main.#{c} ->> '#{subc}' as \"#{c}_#{subc}\""
        end
      end
    elsif !excludes.include?(c)
      assoc = klass.reflections.find { |(_n, h)| h.foreign_key == c }
      if assoc && assoc[1].klass.columns_hash['name']
        table_name = assoc[1].table_name
        jointabs[table_name] ||= 0
        jointabs[table_name] += 1
        tn_alias = "#{table_name}#{jointabs[table_name]}"
        joins.push "left join #{table_name} #{tn_alias} on main.#{c} " +
                   "= #{tn_alias}.id"
        target_name = c.gsub(/_id$/, '_name')
        columns.push "#{tn_alias}.name as #{target_name}"
        extras.each do |(table, column, new_colname)|
          columns.push "#{tn_alias}.#{column} as #{new_colname}" if
            table == table_name
        end
      else
        columns.push "main.#{c}"
      end
    end
  end
  File.open(File.join(target_dir, "#{target_view}.sql"), 'w') do |f|
    f.puts <<EOSQL
create or replace function f_fixfalse(s text) returns text as $$
begin
  return case when s = 'false' then null else s end;
end
$$ language plpgsql;

drop view if exists #{target_view};
create or replace view #{target_view} as
select
  #{columns.join(",\n    ")}
from #{klass.table_name} main
  #{joins.join("\n    ")};

grant select on #{target_view} to public;
EOSQL
  end
end

Instance Method Details

#add_fk(from_table, to_table, options = {}) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/marty/migrations.rb', line 57

def add_fk(from_table, to_table, options = {})
  options[:column] ||= "#{to_table.to_s.singularize}_id"

  from_table = "#{tb_prefix}#{from_table}" unless
    from_table.to_s.start_with?(tb_prefix)

  # FIXME: so hacky to specifically check for "marty_"
  to_table = "#{tb_prefix}#{to_table}" unless
    to_table.to_s.start_with?(tb_prefix) ||
    to_table.to_s.start_with?('marty_')

  add_foreign_key(from_table,
                  to_table,
                  fk_opts(from_table,
                          to_table,
                          options[:column]).update(options),
                 )
end

#add_mcfly_index(tb, *attrs) ⇒ Object



83
84
85
86
87
88
89
90
91
92
# File 'lib/marty/migrations.rb', line 83

def add_mcfly_index(tb, *attrs)
  tb = "#{tb_prefix}#{tb}" unless
    tb.to_s.start_with?(tb_prefix)

  add_mcfly_attrs_index(tb, *attrs)

  MCFLY_INDEX_COLUMNS.each do |a|
    add_index tb.to_sym, a, index_opts(tb, a)
  end
end

#add_mcfly_unique_index(klass) ⇒ Object



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/marty/migrations.rb', line 94

def add_mcfly_unique_index(klass)
  raise "bad class arg #{klass}" unless
    klass.is_a?(Class) && klass < ActiveRecord::Base

  attrs = get_attrs(klass)

  add_index(klass.table_name.to_sym,
            attrs,
            unique: true,
            name: unique_index_name(klass)
           ) unless index_exists?(klass.table_name.to_sym,
                                  attrs,
                                  name: unique_index_name(klass),
                                  unique: true)
end

#get_old_enum_id(klass, name) ⇒ Object

some migrations attempt to get the id using the model. after enumification models have no notion of numeric id we have to get it from the database



255
256
257
258
259
260
261
# File 'lib/marty/migrations.rb', line 255

def get_old_enum_id(klass, name)
  ActiveRecord::Base.
             connection.execute(<<-SQL).to_a.first.try { |v| v['id'] }
    select id from #{klass.table_name} where name =
       #{ActiveRecord::Base.connection.quote(name)}
  SQL
end

#new_enum(klass, prefix_override = nil) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/marty/migrations.rb', line 6

def new_enum(klass, prefix_override = nil)
  raise "bad class arg #{klass}" unless
    klass.is_a?(Class) && klass < ActiveRecord::Base

  raise 'model class needs VALUES (as Set)' unless
    klass.const_defined?(:VALUES)

  values = klass.values
  str_values =
    values.map { |v| ActiveRecord::Base.connection.quote v }.join ','

  # hacky way to get name
  prefix = prefix_override || tb_prefix
  enum_name = klass.table_name.sub(/^#{prefix}_*/, '')

  execute <<-SQL
    CREATE TYPE #{enum_name} AS ENUM (#{str_values});
  SQL
end

#remove_mcfly_unique_index(klass) ⇒ Object



110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/marty/migrations.rb', line 110

def remove_mcfly_unique_index(klass)
  raise "bad class arg #{klass}" unless
    klass.is_a?(Class) && klass < ActiveRecord::Base

  attrs = get_attrs(klass)

  remove_index(klass.table_name.to_sym,
               name: unique_index_name(klass)
              ) if index_exists?(klass.table_name.to_sym,
                                 attrs,
                                 name: unique_index_name(klass),
                                 unique: true)
end

#tb_prefixObject



2
3
4
# File 'lib/marty/migrations.rb', line 2

def tb_prefix
  'marty_'
end

#update_enum(klass, prefix_override = nil) ⇒ Object

NOTE: calling migrations need to disable_ddl_transaction!



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
# File 'lib/marty/migrations.rb', line 27

def update_enum(klass, prefix_override = nil)
  raise "bad class arg #{klass}" unless
    klass.is_a?(Class) && klass < ActiveRecord::Base

  raise 'model class needs VALUES (as Set)' unless
    klass.const_defined?(:VALUES)

  # hacky way to get name
  prefix = prefix_override || tb_prefix
  enum_name = klass.table_name.sub(/^#{prefix}/, '')

  # check values against underlying values
  res = execute <<-SQL
    SELECT ENUM_RANGE(null::#{enum_name});
  SQL

  db_values = res.first['enum_range'].gsub(/[{"}]/, '').split(',')
  ex_values = klass.values.map(&:to_s) - db_values

  return if ex_values.empty?

  ex_values.each do |v|
    prepped_v = ActiveRecord::Base.connection.quote(v)

    execute <<-SQL
      ALTER TYPE #{enum_name} ADD VALUE #{prepped_v};
    SQL
  end
end