Module: Fixturing

Defined in:
lib/fixturing.rb

Class Method Summary collapse

Class Method Details

.beautify_fixture_ids(options = {}) ⇒ Object

Adds model conform fixture ids In STI, fixture name are rewritten with name of model Example: product_153 will become plant_009


297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/fixturing.rb', line 297

def beautify_fixture_ids(options = {})
  path = options[:path] || directory
  # Load and prepare fixtures
  data = {}
  model_ids = {}
  Ekylibre::Schema.tables.each do |table, _columns|
    records = YAML.load_file(path.join("#{table}.yml"))
    base_model = table.to_s.classify
    counter = {}
    data[table.to_s] = records.values.sort { |a, b| [a['type'] || base_model, a['id']] <=> [b['type'] || base_model, b['id']] }.each_with_object({}) do |attributes, hash|
      model = attributes['type'] ? attributes['type'].underscore.pluralize : table.to_s
      counter[model] ||= 0
      counter[model] += 1
      hash["#{model}_#{counter[model].to_s.rjust(3, '0')}"] = attributes
      hash
    end
  end

  data.each do |table, records|
    records.each do |record, attributes|
      data[table][record] = attributes.sort_by(&:first).each_with_object({}) do |pair, hash|
        hash[pair.first] = pair.second
        hash
      end
    end
  end

  # Write
  Ekylibre::Schema.tables.each do |table, _columns|
    File.open(path.join("#{table}.yml"), 'wb') do |f|
      f.write data[table].to_yaml
    end
  end
end

.columnize_keysObject

Convert reflection to hard representation in fixtures

my_thing: things_001             => my_thing_id: 1
my_polymorph: things_001 (Thing) => my_polymorph_id: 1
                                    my_polymorph_type: Thing

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
182
183
184
185
186
187
188
189
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
# File 'lib/fixturing.rb', line 150

def columnize_keys
  # Load and prepare fixtures
  data = {}
  Ekylibre::Schema.tables.each do |table, _columns|
    records = YAML.load_file(directory.join("#{table}.yml"))
    ids = records.values.collect { |a| a['id'] }.compact.map(&:to_i)
    records.each do |record, attributes|
      next if attributes['id']
      id = record.split('_').last.to_i
      attributes['id'] = ids.include?(id) ? (1..(ids.max + 10)).to_a.detect { |x| !ids.include?(x) } : id
      ids << attributes['id']
    end
    data[table.to_s] = records
  end

  # Convert
  Ekylibre::Schema.tables.each do |table, columns|
    columns.each do |column, definition|
      next unless references = definition[:references]
      if references.is_a?(Symbol)
        # Standard reflection case
        foreign_model = references.to_s.camelcase.constantize
        puts references.inspect.red unless data[foreign_model.table_name]
        data[table.to_s].each do |record, attributes|
          reflection = column.to_s.gsub(/\_id\z/, '')
          next unless fixture_id = attributes[reflection]
          if attrs = data[foreign_model.table_name][fixture_id]
            attributes[column.to_s] = attrs['id']
          else
            raise "Cannot find #{fixture_id} for #{references} in #{table}##{record}"
          end
          attributes.delete(reflection)
        end
      else
        # Polymorphic reflection case
        data[table.to_s].each do |record, attributes|
          reflection = column.to_s.gsub(/\_id\z/, '')
          next unless attributes[reflection]
          type_column = reflection + '_type'
          fixture_id, class_name = attributes[reflection].split(/[\(\)\s]+/)[0..1]
          foreign_model = class_name.constantize
          if attrs = data[foreign_model.table_name][fixture_id]
            attributes[column.to_s] = attrs['id']
            attributes[type_column] = foreign_model.name
          else
            raise "Cannot find #{fixture_id} for #{references} in #{table}##{record}"
          end
          attributes.delete(reflection)
        end
      end
    end
    data[table.to_s].each do |record, attributes|
      data[table.to_s][record] = attributes.sort_by(&:first).each_with_object({}) do |pair, hash|
        hash[pair.first] = pair.second
        hash
      end
    end
  end

  # Write
  Ekylibre::Schema.tables.each do |table, _columns|
    File.open(directory.join("#{table}.yml"), 'wb') do |f|
      f.write data[table].to_yaml
    end
  end

  # Clean
  Clean::Annotations.run(only: :fixtures, verbose: false)
end

.convert_value(value, type = :string) ⇒ Object


344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
# File 'lib/fixturing.rb', line 344

def convert_value(value, type = :string)
  value = value.to_s
  value = if type == :float
            value.to_f
          elsif type == :geometry || type == :st_point || type == :point || type == :multi_polygon
            Charta.new_geometry(value).to_ewkt
          elsif type == :decimal
            value.to_f
          elsif type == :integer
            value.to_i
          elsif type == :date
            value.to_date
          elsif type == :datetime
            value.to_time(:utc)
          elsif type == :boolean
            (%w[1 t T true yes TRUE].include?(value) ? true : false)
          elsif type == :json || type == :jsonb
            JSON.parse(value)
          else
            puts "Unknown type to parse in fixtures: #{type.inspect}".red unless %i[text string uuid].include?(type)
            return value unless value =~ /\A\-\-\-(\s+|\z)/
            YAML.safe_load(
              value,
              [
                ActionController::Parameters,
                ActiveSupport::HashWithIndifferentAccess,
                Symbol,
                Time,
                BigDecimal,
                RGeo::Geos::CAPIGeometryCollectionImpl,
                RGeo::Geos::CAPIFactory,
                RGeo::Geos::CAPIMultiPolygonImpl,
                OpenStruct,
                RGeo::Geos::CAPIPointImpl,
                RGeo::Geos::CAPIPolygonImpl,
                RGeo::Cartesian::MultiPolygonImpl,
                RGeo::Cartesian::Factory
              ]
            )
          end
  value
end

.current_versionObject


5
6
7
# File 'lib/fixturing.rb', line 5

def current_version
  CSV.read(migrations_file).last.first.to_i
end

.directoryObject


9
10
11
# File 'lib/fixturing.rb', line 9

def directory
  Pathname.new(ActiveRecord::Tasks::DatabaseTasks.fixtures_path)
end

.dump(tenant, options = {}) ⇒ Object

Dump data of database into fixtures


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
# File 'lib/fixturing.rb', line 60

def dump(tenant, options = {})
  Ekylibre::Tenant.switch!(tenant)

  migrate(tenant) unless up_to_date?

  if options[:backup]
    backup = "#{directory}~"
    FileUtils.rm_rf(backup)
    FileUtils.cp_r(directory, backup)
  end

  Dir[directory.join('*.yml').to_s].each do |f|
    FileUtils.rm_rf(f)
  end

  version = extract(path: directory)

  # Updates fixtures name with models
  beautify_fixture_ids(path: directory)

  # Clean annotations
  Clean::Annotations.run(only: :fixtures, verbose: false)

  # Dump last schema_migrations into schema_migrations file
  File.open(migrations_file, 'wb') do |f|
    f.write version
  end
end

.extract(options = {}) ⇒ Object

Extract data from DB into given path or test/fixtures by default Returns version of DB (as integer)


91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/fixturing.rb', line 91

def extract(options = {})
  path = options[:path] || directory
  Ekylibre::Schema.tables.each do |table, columns|
    records = {}
    sort_column = %w[id number name].detect { |column| ActiveRecord::Base.connection.column_exists?(table, column) }
    ActiveRecord::Base.connection.select_all("SELECT * FROM #{table} #{sort_column ? 'ORDER BY ' + sort_column : ''}").each do |row|
      record = {}
      row.sort.each do |attribute, value|
        if columns[attribute]
          unless value.nil?
            type = columns[attribute].type
            type = columns[attribute].limit[:type] if columns[attribute].limit.is_a?(Hash)
            record[attribute] = convert_value(value, type.to_sym)
          end
        else
          puts "Cannot find column '#{attribute}' in #{table}. Run `rake clean:schema`.".red
        end
      end
      records["#{table}_#{row['id'].rjust(3, '0')}"] = record
    end

    File.open(path.join("#{table}.yml"), 'wb') do |f|
      f.write records.to_yaml.gsub(/[\ \t]+\n/, "\n")
    end
  end

  version = ActiveRecord::Base.connection.select_value("SELECT * FROM #{migrations_table} ORDER BY 1 DESC")
  version.to_i
end

.migrate(tenant, options = {}) ⇒ Object


121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/fixturing.rb', line 121

def migrate(tenant, options = {})
  target = ActiveRecord::Migrator.last_version
  origin = options[:origin] || current_version
  if target != origin
    say 'Migrate fixtures from ' + origin.inspect + ' to ' + target.inspect
    Ekylibre::Tenant.switch(tenant) do
      ActiveRecord::Migrator.migrate(ActiveRecord::Migrator.migrations_paths, target)
    end
  else
    say 'No more migrations', :green
  end
end

.migrations_fileObject


13
14
15
# File 'lib/fixturing.rb', line 13

def migrations_file
  directory.join(migrations_table)
end

.migrations_tableObject


17
18
19
# File 'lib/fixturing.rb', line 17

def migrations_table
  'schema_migrations'
end

.reflectionize_keysObject

Reverse of #columnize_keys Fixtures are expected with ids !


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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/fixturing.rb', line 222

def reflectionize_keys
  # Load and prepare fixtures
  data = {}
  model_ids = {}
  Ekylibre::Schema.tables.each do |table, _columns|
    records = YAML.load_file(directory.join("#{table}.yml"))
    base_model = table.to_s.classify
    counter = {}
    data[table.to_s] = records.values.sort { |a, b| [a['type'] || base_model, a['id']] <=> [b['type'] || base_model, b['id']] }.each_with_object({}) do |attributes, hash|
      model = attributes['type'] ? attributes['type'].underscore.pluralize : table.to_s
      counter[model] ||= 0
      counter[model] += 1
      hash["#{model}_#{counter[model].to_s.rjust(3, '0')}"] = attributes
      hash
    end
  end

  # Convert
  Ekylibre::Schema.tables.each do |table, columns|
    columns.each do |column, definition|
      next unless references = definition[:references]
      if references.is_a?(Symbol)
        # Standard reflection case
        foreign_model = references.to_s.camelcase.constantize
        puts references.inspect.red unless data[foreign_model.table_name]
        data[table.to_s].each do |record, attributes|
          next unless fixture_id = attributes[column.to_s]
          if attrs = data[foreign_model.table_name].detect { |_r, a| a['id'] == fixture_id }
            attributes[column.to_s.gsub(/\_id\z/, '')] = attrs.first
          else
            raise "Cannot find #{foreign_model.name} #{fixture_id} for #{column} in #{table}##{record}"
          end
          attributes.delete(column.to_s)
        end
      else
        # Polymorphic reflection case
        data[table.to_s].each do |record, attributes|
          type_column = column.to_s.gsub(/\_id\z/, '') + '_type'
          next unless (fixture_id = attributes[column.to_s]) && (fixture_type = attributes[type_column])
          foreign_model = fixture_type.constantize
          if attrs = data[foreign_model.table_name].detect { |_r, a| a['id'] == fixture_id && (a['type'] || foreign_model.name) == fixture_type }
            attributes[column.to_s.gsub(/\_id\z/, '')] = "#{attrs.first} (#{fixture_type})"
          else
            raise "Cannot find #{fixture_type}##{fixture_id} for #{column} in #{table}##{record} (#{attributes['id']})"
          end
          attributes.delete(column.to_s)
          attributes.delete(type_column)
        end
      end
    end
  end

  data.each do |table, records|
    records.each do |record, attributes|
      data[table][record] = attributes.delete_if { |k, _v| k == 'id' }.sort_by(&:first).each_with_object({}) do |pair, hash|
        hash[pair.first] = pair.second
        hash
      end
    end
  end

  # Write
  Ekylibre::Schema.tables.each do |table, _columns|
    File.open(directory.join("#{table}.yml"), 'wb') do |f|
      f.write data[table].to_yaml
    end
  end

  # Clean
  Clean::Annotations.run(only: :fixtures, verbose: false)
end

.restore(tenant, options = {}) ⇒ Object


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

def restore(tenant, options = {})
  path = options[:path] || directory
  version = options[:version] || current_version
  verbose = !options[:verbose].is_a?(FalseClass)
  Ekylibre::Tenant.create_database_for!(tenant)
  Ekylibre::Tenant.switch_to_database_for(tenant)
  Apartment.connection.execute("DROP SCHEMA IF EXISTS \"#{tenant}\" CASCADE")
  Apartment.connection.execute("CREATE SCHEMA \"#{tenant}\"")
  Ekylibre::Tenant.add(tenant)
  Apartment.connection.execute("SET search_path TO '#{tenant}', postgis")
  Ekylibre::Tenant.migrate(tenant, to: version)
  table_names = tables_from_files(path: path)
  say 'Load fixtures' if verbose
  Ekylibre::Tenant.switch!(tenant)
  ActiveRecord::FixtureSet.reset_cache
  ActiveRecord::Base.connection.schema_cache.clear!
  ActiveRecord::FixtureSet.create_fixtures(path, table_names)
  migrate(tenant, origin: version) unless up_to_date?(version: version)
end

.reverse(tenant, steps = 1) ⇒ Object


54
55
56
57
# File 'lib/fixturing.rb', line 54

def reverse(tenant, steps = 1)
  restore(tenant)
  rollback(tenant, steps)
end

.rollback(tenant, steps = 1) ⇒ Object


134
135
136
137
138
139
# File 'lib/fixturing.rb', line 134

def rollback(tenant, steps = 1)
  say "Rollback (Steps count: #{steps})"
  Ekylibre::Tenant.switch(tenant) do
    ActiveRecord::Migrator.rollback(ActiveRecord::Migrator.migrations_paths, steps)
  end
end

.say(text, color = :yellow) ⇒ Object


141
142
143
144
# File 'lib/fixturing.rb', line 141

def say(text, color = :yellow)
  size = text.size
  puts '== ' + text.send(color) + ' ' + '=' * (79 - size - 4) + "\n\n"
end

.tables_from_files(options = {}) ⇒ Object


27
28
29
30
31
32
# File 'lib/fixturing.rb', line 27

def tables_from_files(options = {})
  path = options[:path] || directory
  Dir.glob(path.join('*.yml')).collect do |f|
    Pathname.new(f).basename('.*').to_s
  end.sort
end

.up_to_date?(options = {}) ⇒ Boolean

Returns true if current_version is last DB version

Returns:

  • (Boolean)

22
23
24
25
# File 'lib/fixturing.rb', line 22

def up_to_date?(options = {})
  version = options[:version] || current_version
  version == ActiveRecord::Migrator.last_version
end

.yaml_escape(value, type = :string) ⇒ Object


332
333
334
335
336
337
338
339
340
341
342
# File 'lib/fixturing.rb', line 332

def yaml_escape(value, type = :string)
  value = value.to_s
  value = if type == :float || type == :decimal || type == :integer
            value
          elsif type == :boolean
            (%w[1 t T true yes TRUE].include?(value) ? 'true' : 'false')
          else
            value.to_yaml.gsub(/^\-\-\-\s*/, '').strip
          end
  value
end