Class: PseudoCleaner::TableCleaner

Inherits:
Object
  • Object
show all
Defined in:
lib/pseudo_cleaner/table_cleaner.rb

Constant Summary collapse

@@initial_states =
{}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(start_method, end_method, table, options = {}) ⇒ TableCleaner

Returns a new instance of TableCleaner.



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
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 19

def initialize(start_method, end_method, table, options = {})
  raise "You must specify a table object." unless table
  unless PseudoCleaner::MasterCleaner::VALID_START_METHODS.include?(start_method)
    raise "You must specify a valid start function from: #{PseudoCleaner::MasterCleaner::VALID_START_METHODS}."
  end
  unless PseudoCleaner::MasterCleaner::VALID_END_METHODS.include?(end_method)
    raise "You must specify a valid end function from: #{PseudoCleaner::MasterCleaner::VALID_END_METHODS}."
  end

  @table = table

  @@initial_states[@table] ||= {}
  initial_state            = @@initial_states[@table]

  @options = options

  @options[:table_start_method] ||= start_method
  @options[:table_end_method]   ||= end_method
  @options[:output_diagnostics] ||= PseudoCleaner::Configuration.current_instance.output_diagnostics ||
      PseudoCleaner::Configuration.current_instance.post_transaction_analysis

  unless initial_state.has_key?(:table_is_active_record)
    initial_state[:table_is_active_record] = false

    if Object.const_defined?("ActiveRecord", false) && ActiveRecord.const_defined?("Base", false)
      if symbol_table?
        initial_state[:table_is_active_record] = true
        initial_state[:table_name]             = table
      else
        table_super_class = table.superclass

        while !initial_state[:table_is_active_record] && table_super_class
          initial_state[:table_is_active_record] = (table_super_class == ActiveRecord::Base)
          initial_state[:table_name]             = table.name if initial_state[:table_is_active_record]
          table_super_class                      = table_super_class.superclass
        end
      end
    end
  end

  unless initial_state.has_key?(:table_is_sequel_model)
    initial_state[:table_is_sequel_model] = false

    if Object.const_defined?("Sequel", false) && Sequel.const_defined?("Model", false)
      if symbol_table?
        initial_state[:table_is_sequel_model] = PseudoCleaner::Configuration.db_connection(:sequel)[table]
        initial_state[:table_name]            = table
      else
        table_super_class = table.superclass

        while !initial_state[:table_is_sequel_model] && table_super_class
          initial_state[:table_is_sequel_model] = (table_super_class == Sequel::Model)
          initial_state[:table_name]            = table.name if initial_state[:table_is_sequel_model]
          table_super_class                     = table_super_class.superclass
        end
      end
    end
  end
end

Instance Attribute Details

#tableObject

Returns the value of attribute table.



3
4
5
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 3

def table
  @table
end

Instance Method Details

#<=>(other_object) ⇒ Object



636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 636

def <=>(other_object)
  if (other_object.is_a?(PseudoCleaner::TableCleaner))
    return 0 if other_object.table == self.table

    SortedSeeder::Seeder.create_order.each do |create_table|
      if create_table == self.table
        return -1
      elsif create_table == other_object.table
        return 1
      end
    end
  else
    if other_object.respond_to?(:<=>)
      comparison = (other_object <=> self)
      if comparison
        return -1 * comparison
      end
    end
  end

  return -1
end

#active_record_tableObject



165
166
167
168
169
170
171
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 165

def active_record_table
  if symbol_table?
    table
  else
    table.table_name
  end
end

#ignore_updatesObject



449
450
451
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 449

def ignore_updates
  false
end

#output_delete_record(test_strategy, stats_string, table_label, table_value, pre_string, require_output = false) ⇒ Object



554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 554

def output_delete_record(test_strategy,
                         stats_string,
                         table_label,
                         table_value,
                         pre_string,
                         require_output = false)
  if pre_string && !@report_table && (@options[:output_diagnostics] || require_output)
    PseudoCleaner::Logger.write(pre_string)
  end

  if test_strategy == :transaction
    PseudoCleaner::Logger.write("    ***** TRANSACTION FAILED!!! *****".red.on_light_white)
  end

  if @options[:output_diagnostics] || require_output
    PseudoCleaner::MasterCleaner.report_error

    if @report_table
      @report_table.write_stats(table_label, table_value)
    else
      PseudoCleaner::Logger.write(stats_string)
    end
  end

  nil
end

#peek_valuesObject



768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 768

def peek_values
  row_data      = []
  peek_name     = nil
  initial_state = @@initial_states[@table]

  time = Benchmark.measure do
    puts "  TableCleaner(#{initial_state[:table_name]})" if PseudoCleaner::Configuration.instance.benchmark


    review_rows do |table_name, table_values|
      peek_name = table_name
      row_data << table_values
    end

    if row_data && !row_data.empty?
      output_values = false

      if PseudoCleaner::MasterCleaner.report_table
        Cornucopia::Util::ReportTable.new(nested_table:         PseudoCleaner::MasterCleaner.report_table,
                                          nested_table_label:   peek_name,
                                          suppress_blank_table: true) do |report_table|
          row_data.each_with_index do |row, row_index|
            report_table.write_stats row_index.to_s, row
          end
        end
      else
        PseudoCleaner::Logger.write("  #{peek_name}")

        row_data.each_with_index do |updated_value, index|
          PseudoCleaner::Logger.write("    #{index}: #{updated_value}")
        end
      end

      PseudoCleaner::MasterCleaner.report_error
    end
  end

  puts "  TableCleaner(#{initial_state[:table_name]}) time: #{time}" if PseudoCleaner::Configuration.instance.benchmark
end

#reset_auto_increment(test_start) ⇒ Object



581
582
583
584
585
586
587
588
589
590
591
592
593
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 581

def reset_auto_increment test_start
  initial_state = @@initial_states[@table]

  if test_start
    if initial_state[:table_is_active_record]
      reset_auto_increment_active_record
    end

    if initial_state[:table_is_sequel_model]
      reset_auto_increment_sequel_model
    end
  end
end

#reset_auto_increment_active_recordObject



595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 595

def reset_auto_increment_active_record
  initial_state = @@initial_states[@table]

  if initial_state[:max_id]
    table_name = active_record_table

    unless table_name.blank?
      if @options[:output_diagnostics]
        if @report_table
          @report_table.write_stats("AUTO_INCREMENT", initial_state[:max_id] + 1)
        else
          PseudoCleaner::Logger.write("    ALTER TABLE #{table_name} AUTO_INCREMENT = #{initial_state[:max_id] + 1}")
        end
      end

      PseudoCleaner::Configuration.db_connection(:active_record).connection.
          execute("ALTER TABLE #{table_name} AUTO_INCREMENT = #{initial_state[:max_id] + 1}")
    end
  end
end

#reset_auto_increment_sequel_modelObject



616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 616

def reset_auto_increment_sequel_model
  initial_state = @@initial_states[@table]

  if initial_state[:max_id]
    table_name = sequel_model_table_name

    unless table_name.blank?
      if @options[:output_diagnostics]
        if @report_table
          @report_table.write_stats("AUTO_INCREMENT", initial_state[:max_id] + 1)
        else
          PseudoCleaner::Logger.write("    ALTER TABLE #{table_name} AUTO_INCREMENT = #{initial_state[:max_id] + 1}")
        end
      end

      PseudoCleaner::Configuration.db_connection(:sequel)["ALTER TABLE #{table_name} AUTO_INCREMENT = #{initial_state[:max_id] + 1}"].first
    end
  end
end

#reset_suiteObject



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 7

def reset_suite
  initial_state = @@initial_states[@table]

  time = Benchmark.measure do
    puts "  TableCleaner(#{initial_state[:table_name]})" if PseudoCleaner::Configuration.instance.benchmark

    @@initial_states = {}
  end

  puts "  TableCleaner(#{initial_state[:table_name]}) time: #{time}" if PseudoCleaner::Configuration.instance.benchmark
end

#reset_table(test_strategy, require_output, is_suite_end) ⇒ Object



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
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 297

def reset_table test_strategy, require_output, is_suite_end
  initial_state = @@initial_states[@table]

  time = Benchmark.measure do
    puts "  TableCleaner(#{initial_state[:table_name]})" if PseudoCleaner::Configuration.instance.benchmark


    if @test_strategy != test_strategy && !PseudoCleaner::Configuration.current_instance.single_cleaner_set
      if @options[:output_diagnostics]
        PseudoCleaner::MasterCleaner.report_error

        if @report_table
          @report_table.write_stats("WARNING", "*** The ending strategy for \"#{initial_state[:table_name]}\" changed! ***")
        else
          PseudoCleaner::Logger.write("  *** The ending strategy for \"#{initial_state[:table_name]}\" changed! ***".red.on_light_white)
        end
      end
    end

    if test_strategy == :pseudo_delete || PseudoCleaner::Configuration.current_instance.post_transaction_analysis
      # we should check the relationships for any records which still refer to
      # a now deleted record.  (i.e. if we updated a record to refer to a record)
      # we deleted...
      #
      # Which is why this is not a common or particularly good solution.
      #
      # I'm using it because it is faster than reseeding each test...
      # And, I can be responsible for worrying about referential integrity in the test
      # if I want to...
      pre_string = "  Resetting table \"#{initial_state[:table_name]}\" for #{test_strategy}..."
      pre_string = "Tests ended without cleaning up properly!!!\n" + pre_string if require_output
      pre_string = pre_string.red.on_light_white if require_output

      require_output ||= @options[:output_diagnostics]

      if initial_state[:table_is_active_record]
        test_end_active_record test_strategy, pre_string, require_output, is_suite_end
      end

      if initial_state[:table_is_sequel_model]
        test_end_sequel_model test_strategy, pre_string, require_output, is_suite_end
      end
    end
  end

  puts "  TableCleaner(#{initial_state[:table_name]}) time: #{time}" if PseudoCleaner::Configuration.instance.benchmark
end

#review_rows(&block) ⇒ Object



691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 691

def review_rows(&block)
  initial_state = @@initial_states[@table]

  time = Benchmark.measure do
    puts "  TableCleaner(#{initial_state[:table_name]})" if PseudoCleaner::Configuration.instance.benchmark


    if initial_state
      if initial_state[:table_is_active_record]
        review_rows_active_record &block
      end

      if initial_state[:table_is_sequel_model]
        review_rows_sequel_model &block
      end
    end
  end

  puts "  TableCleaner(#{initial_state[:table_name]}) time: #{time}" if PseudoCleaner::Configuration.instance.benchmark
end

#review_rows_active_record(&block) ⇒ Object



712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 712

def review_rows_active_record(&block)
  initial_state  = @@initial_states[@table]
  table_name     = active_record_table
  dataset_sequel = nil

  if initial_state[:max_id]
    the_max = initial_state[:max_id] || 0

    dataset_sequel = "SELECT * FROM `#{table_name}` WHERE id > #{the_max}"
  elsif initial_state[:created]
    dataset_sequel = "SELECT * FROM `#{table_name}` WHERE #{initial_state[:created][:column_name]} > '#{initial_state[:created][:value]}'"
  elsif initial_state[:updated]
    dataset_sequel = "SELECT * FROM `#{table_name}` WHERE #{initial_state[:updated][:column_name]} > '#{initial_state[:updated][:value]}'"
  elsif initial_state[:count]
    dataset_sequel = "SELECT * FROM `#{table_name}` LIMIT 99 OFFSET #{initial_state[:count]}"
  end

  columns = PseudoCleaner::Configuration.db_connection(:active_record).connection.columns(table_name)
  PseudoCleaner::Configuration.db_connection(:active_record).connection.execute(dataset_sequel).each do |row|
    col_index = 0
    data_hash = columns.reduce({}) do |hash, column_name|
      hash[column_name.name] = row[col_index]
      col_index              += 1

      hash
    end

    block.yield table_name, data_hash
  end
end

#review_rows_sequel_model(&block) ⇒ Object



743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 743

def review_rows_sequel_model(&block)
  initial_state = @@initial_states[@table]
  dataset       = nil

  if initial_state[:max_id]
    dataset = sequel_model_table.unfiltered.where { id > initial_state[:max_id] || 0 }
  elsif initial_state[:created]
    dataset = sequel_model_table.
        unfiltered.
        where("`#{initial_state[:created][:column_name]}` > ?", initial_state[:created][:value])
  elsif initial_state[:updated]
    dataset = sequel_model_table.
        unfiltered.
        where("`#{initial_state[:updated][:column_name]}` > ?", initial_state[:updated][:value])
  elsif initial_state[:count]
    dataset = sequel_model_table.unfiltered.limit(99, initial_state[:count])
  end

  if dataset
    dataset.each do |row|
      block.yield sequel_model_table_name.gsub(/`([^`]+)`/, "\\1"), row
    end
  end
end

#save_stateObject



123
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
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 123

def save_state
  initial_state = @@initial_states[@table]

  if @test_strategy == :pseudo_delete && !initial_state[:saved]
    initial_state[:saved] = true

    within_report_block(initial_state[:table_name], @options[:output_diagnostics]) do
      if @options[:output_diagnostics]
        PseudoCleaner::MasterCleaner.report_error

        unless @report_table
          PseudoCleaner::Logger.write("  Gathering information about \"#{initial_state[:table_name]}\"...".blue.on_light_white)
        end
      end

      if initial_state[:table_is_active_record]
        test_start_active_record @test_strategy
      end

      if initial_state[:table_is_sequel_model]
        test_start_sequel_model @test_strategy
      end

      if PseudoCleaner::Configuration.current_instance.reset_auto_increment
        reset_auto_increment !PseudoCleaner::Configuration.current_instance.clean_database_before_tests
      end

      if initial_state.has_key?(:count) && @options[:output_diagnostics]
        if @report_table
          @report_table.write_stats "", "*** There are no columns to track inserts and updates easily on for #{initial_state[:table_name]} ***"
        else
          PseudoCleaner::Logger.write("    *** There are no columns to track inserts and updates easily on for #{initial_state[:table_name]} ***".red.on_light_white)
        end
      end
    end
  end
end

#sequel_model_tableObject



659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 659

def sequel_model_table
  table_dataset = nil

  if symbol_table?
    table_dataset = PseudoCleaner::Configuration.db_connection(:sequel)[table]
  else
    if sequel_model_table_name
      table_dataset = PseudoCleaner::Configuration.db_connection(:sequel)[sequel_model_table_name.gsub(/`([^`]+)`/, "\\1").to_sym]
    end
    unless table_dataset && table_dataset.is_a?(Sequel::Mysql2::Dataset)
      table_dataset = table.dataset
    end
  end
  unless table_dataset && table_dataset.is_a?(Sequel::Mysql2::Dataset)
    table_dataset = nil
  end

  table_dataset
end

#sequel_model_table_nameObject



679
680
681
682
683
684
685
686
687
688
689
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 679

def sequel_model_table_name
  if symbol_table?
    "`#{table}`"
  elsif table.simple_table
    table.simple_table
  elsif table.table_name
    "`#{table.table_name}`"
  else
    nil
  end
end

#suite_end(test_strategy) ⇒ Object



282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 282

def suite_end test_strategy
  initial_state = @@initial_states[@table]

  time = Benchmark.measure do
    puts "  TableCleaner(#{initial_state[:table_name]})" if PseudoCleaner::Configuration.instance.benchmark


    within_report_block(initial_state[:table_name], @options[:output_diagnostics]) do
      reset_table test_strategy, true, true
    end
  end

  puts "  TableCleaner(#{initial_state[:table_name]}) time: #{time}" if PseudoCleaner::Configuration.instance.benchmark
end

#suite_start(test_strategy) ⇒ Object



92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 92

def suite_start test_strategy
  @test_strategy ||= test_strategy
  initial_state  = @@initial_states[@table]

  time = Benchmark.measure do
    puts "  TableCleaner(#{initial_state[:table_name]})" if PseudoCleaner::Configuration.instance.benchmark

    save_state
  end

  puts "  TableCleaner(#{initial_state[:table_name]}) time: #{time}" if PseudoCleaner::Configuration.instance.benchmark
end

#symbol_table?Boolean

Returns:

  • (Boolean)


161
162
163
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 161

def symbol_table?
  table.is_a?(String) || table.is_a?(Symbol)
end

#test_end(test_strategy) ⇒ Object



267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 267

def test_end test_strategy
  initial_state = @@initial_states[@table]

  time = Benchmark.measure do
    puts "  TableCleaner(#{initial_state[:table_name]})" if PseudoCleaner::Configuration.instance.benchmark


    within_report_block(initial_state[:table_name], @options[:output_diagnostics]) do
      reset_table test_strategy, false, false
    end
  end

  puts "  TableCleaner(#{initial_state[:table_name]}) time: #{time}" if PseudoCleaner::Configuration.instance.benchmark
end

#test_end_active_record(test_strategy, pre_string, require_output, is_suite_end) ⇒ Object



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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 345

def test_end_active_record test_strategy, pre_string, require_output, is_suite_end
  initial_state = @@initial_states[@table]
  cleaned_table = false

  table_name = active_record_table
  if initial_state[:max_id]
    the_max = initial_state[:max_id] || 0

    PseudoCleaner::Configuration.db_connection(:active_record).connection.
        execute("DELETE FROM `#{table_name}` WHERE id > #{the_max}")
    num_deleted = PseudoCleaner::Configuration.db_connection(:active_record).connection.raw_connection.affected_rows

    if num_deleted > 0
      cleaned_table = true

      pre_string = output_delete_record(test_strategy,
                                        "    Deleted #{num_deleted} records by ID.",
                                        "Deleted",
                                        "#{num_deleted} records by ID",
                                        pre_string,
                                        require_output)
    end
  end

  if initial_state[:created]
    PseudoCleaner::Configuration.db_connection(:active_record).connection.
        execute("DELETE FROM `#{table_name}` WHERE #{initial_state[:created][:column_name]} > '#{initial_state[:created][:value]}'")
    num_deleted = PseudoCleaner::Configuration.db_connection(:active_record).connection.raw_connection.affected_rows

    if num_deleted > 0
      cleaned_table = true

      pre_string = output_delete_record(test_strategy,
                                        "    Deleted #{num_deleted} records by #{initial_state[:created][:column_name]}.",
                                        "Deleted",
                                        "#{num_deleted} records by #{initial_state[:created][:column_name]}",
                                        pre_string,
                                        require_output)
    end
  end

  if initial_state[:updated] && !ignore_updates
    test_value = initial_state[:updated][:value]
    if is_suite_end
      test_value = initial_state[:updated][:initial_value]
    end

    dirty_count = PseudoCleaner::Configuration.db_connection(:active_record).connection.
        execute("SELECT COUNT(*) FROM `#{table_name}` WHERE #{initial_state[:updated][:column_name]} > '#{test_value}'").first[0]

    if dirty_count > 0
      # cleaned_table = true

      initial_state[:updated][:value] = PseudoCleaner::Configuration.db_connection(:active_record).connection.
          execute("SELECT MAX(#{initial_state[:updated][:column_name]}) FROM `#{table_name}`").first[0]

      pre_string = output_delete_record(test_strategy,
                                        "    *** There are #{dirty_count} records which have been updated and may be dirty remaining after cleaning \"#{initial_state[:table_name]}\"... ***".red.on_light_white,
                                        "WARNING",
                                        "*** There are #{dirty_count} records which have been updated and may be dirty remaining after cleaning \"#{initial_state[:table_name]}\"... ***",
                                        pre_string,
                                        require_output)
    end
  end

  final_count = PseudoCleaner::Configuration.db_connection(:active_record).connection.
      execute("SELECT COUNT(*) FROM `#{table_name}`").first[0]
  if initial_state[:count] == 0
    if initial_state[:blank]
      cleaned_table = true

      DatabaseCleaner[:active_record, connection: PseudoCleaner::Configuration.db_connection(:active_record)].
          clean_with(:truncation, only: [initial_state[:table_name]])
      if final_count > 0
        pre_string = output_delete_record(test_strategy,
                                          "    Deleted #{final_count} records by cleaning the table.",
                                          "Deleted",
                                          "#{final_count} records by cleaning the table",
                                          pre_string,
                                          require_output)
      end

      final_count = PseudoCleaner::Configuration.db_connection(:active_record).connection.
          execute("SELECT COUNT(*) FROM `#{table_name}`").first[0]
    end
  end

  if initial_state[:count] != final_count
    pre_string = output_delete_record(test_strategy,
                                      "    *** There are #{final_count - initial_state[:count]} dirty records remaining after cleaning \"#{initial_state[:table_name]}\"... ***".red.on_light_white,
                                      "WARNING",
                                      "*** There are #{final_count - initial_state[:count]} dirty records remaining after cleaning \"#{initial_state[:table_name]}\"... ***",
                                      pre_string,
                                      true)

    initial_state[:count] = final_count
    cleaned_table         = true
  end

  if cleaned_table
    reset_auto_increment true
  end
end

#test_end_sequel_model(test_strategy, pre_string, require_output, is_suite_end) ⇒ Object



453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 453

def test_end_sequel_model test_strategy, pre_string, require_output, is_suite_end
  initial_state = @@initial_states[@table]
  access_table  = sequel_model_table
  cleaned_table = false

  if access_table
    if initial_state[:max_id]
      the_max     = initial_state[:max_id] || 0
      num_deleted = access_table.unfiltered.where { id > the_max }.delete
      if num_deleted > 0
        cleaned_table = true

        pre_string = output_delete_record(test_strategy,
                                          "    Deleted #{num_deleted} records by ID.",
                                          "Deleted",
                                          "#{num_deleted} records by ID",
                                          pre_string,
                                          require_output)
      end
    end

    if initial_state[:created]
      num_deleted = access_table.
          unfiltered.
          where("`#{initial_state[:created][:column_name]}` > ?", initial_state[:created][:value]).
          delete
      if num_deleted > 0
        cleaned_table = true

        pre_string = output_delete_record(test_strategy,
                                          "    Deleted #{num_deleted} records by #{initial_state[:created][:column_name]}.",
                                          "Deleted",
                                          "#{num_deleted} records by #{initial_state[:created][:column_name]}",
                                          pre_string,
                                          require_output)
      end
    end

    if initial_state[:updated] && !ignore_updates
      test_value = initial_state[:updated][:value]
      if is_suite_end
        test_value = initial_state[:updated][:initial_value]
      end

      dirty_count = access_table.
          unfiltered.
          where("`#{initial_state[:updated][:column_name]}` > ?", test_value).
          count

      if dirty_count > 0
        # cleaned_table = true

        initial_state[:updated][:value] = access_table.unfiltered.max(initial_state[:updated][:column_name])

        pre_string = output_delete_record(test_strategy,
                                          "    *** There are #{dirty_count} records which have been updated and may be dirty remaining after cleaning \"#{initial_state[:table_name]}\"... ***".red.on_light_white,
                                          "WARNING",
                                          "*** There are #{dirty_count} records which have been updated and may be dirty remaining after cleaning \"#{initial_state[:table_name]}\"... ***",
                                          pre_string,
                                          require_output)
      end
    end

    final_count = access_table.unfiltered.count
    if initial_state[:count] == 0
      if initial_state[:blank]
        cleaned_table = true

        DatabaseCleaner[:sequel, connection: PseudoCleaner::Configuration.db_connection(:sequel)].
            clean_with(:truncation, only: [initial_state[:table_name]])
        if final_count > 0
          pre_string = output_delete_record(test_strategy,
                                            "    Deleted #{final_count} records by cleaning the table.",
                                            "Deleted",
                                            "#{final_count} records by cleaning the table",
                                            pre_string,
                                            require_output)
        end

        final_count = access_table.unfiltered.count
      end
    end

    if initial_state[:count] != final_count
      pre_string = output_delete_record(test_strategy,
                                        "    *** There are #{final_count - initial_state[:count]} dirty records remaining after cleaning \"#{initial_state[:table_name]}\"... ***".red.on_light_white,
                                        "WARNING",
                                        "*** There are #{final_count - initial_state[:count]} dirty records remaining after cleaning \"#{initial_state[:table_name]}\"... ***",
                                        pre_string,
                                        true)

      initial_state[:count] = final_count
      cleaned_table         = true
    end

    if cleaned_table
      reset_auto_increment true
    end
  end
end

#test_start(test_strategy) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 79

def test_start test_strategy
  @test_strategy ||= test_strategy
  initial_state  = @@initial_states[@table]

  time = Benchmark.measure do
    puts "  TableCleaner(#{initial_state[:table_name]})" if PseudoCleaner::Configuration.instance.benchmark

    save_state
  end

  puts "  TableCleaner(#{initial_state[:table_name]}) time: #{time}" if PseudoCleaner::Configuration.instance.benchmark
end

#test_start_active_record(test_strategy) ⇒ Object



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
219
220
221
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 173

def test_start_active_record test_strategy
  new_state = {}

  table_name = active_record_table
  if PseudoCleaner::Configuration.db_connection(:active_record).connection.columns(table_name).find { |column| column.name == "id" }
    new_state[:max_id] = PseudoCleaner::Configuration.db_connection(:active_record).connection.
        execute("SELECT MAX(`id`) FROM `#{table_name}`").first[0] || 0

    if @options[:output_diagnostics]
      if @report_table
        @report_table.write_stats("max(id)", new_state[:max_id])
      else
        PseudoCleaner::Logger.write("    max(id) = #{new_state[:max_id]}")
      end
    end
  end

  [:created, :updated].each do |date_name|
    [:at, :on].each do |verb_name|
      date_column_name = "#{date_name}_#{verb_name}"

      if PseudoCleaner::Configuration.db_connection(:active_record).connection.
          columns(table_name).find { |column| column.name == date_column_name }
        new_state[date_name]                 = {
            column_name: date_column_name,
            value:       PseudoCleaner::Configuration.db_connection(:active_record).connection.
                execute("SELECT MAX(`#{date_column_name}`) FROM `#{table_name}`").first[0] ||
                             Time.now - 1.second
        }
        new_state[date_name][:initial_value] = new_state[date_name][:value]
        if @options[:output_diagnostics]
          if @report_table
            @report_table.write("max(#{new_state[date_name][:column_name]})", new_state[date_name][:value])
          else
            PseudoCleaner::Logger.write("    max(#{new_state[date_name][:column_name]}) = #{new_state[date_name][:value]}")
          end
        end

        break
      end
    end
  end

  new_state[:blank] = new_state.blank?
  new_state[:count] = PseudoCleaner::Configuration.db_connection(:active_record).connection.
      execute("SELECT COUNT(*) FROM `#{table_name}`").first[0]

  @@initial_states[@table] = @@initial_states[@table].merge new_state
end

#test_start_sequel_model(test_strategy) ⇒ Object



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
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 223

def test_start_sequel_model test_strategy
  new_state    = {}
  access_table = sequel_model_table

  if access_table.columns.include?(:id)
    new_state[:max_id] = access_table.unfiltered.max(:id) || 0
    if @options[:output_diagnostics]
      if @report_table
        @report_table.write_stats("max(id)", new_state[:max_id])
      else
        PseudoCleaner::Logger.write("    max(id) = #{new_state[:max_id]}")
      end
    end
  end

  [:created, :updated].each do |date_name|
    [:at, :on].each do |verb_name|
      date_column_name = "#{date_name}_#{verb_name}".to_sym

      if access_table.columns.include?(date_column_name)
        new_state[date_name]                 = {
            column_name: date_column_name,
            value:       access_table.unfiltered.max(date_column_name) || Time.now - 1.second
        }
        new_state[date_name][:initial_value] = new_state[date_name][:value]
        if @options[:output_diagnostics]
          if @report_table
            @report_table.write_stats("max(#{new_state[date_name][:column_name]})", new_state[date_name][:value])
          else
            PseudoCleaner::Logger.write("    max(#{new_state[date_name][:column_name]}) = #{new_state[date_name][:value]}")
          end
        end

        break
      end
    end
  end

  new_state[:blank] = new_state.blank?
  new_state[:count] = access_table.unfiltered.count

  @@initial_states[@table] = @@initial_states[@table].merge new_state
end

#within_report_block(description, conditional, &block) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/pseudo_cleaner/table_cleaner.rb', line 105

def within_report_block(description, conditional, &block)
  @report_table = nil

  if PseudoCleaner::MasterCleaner.report_table || conditional
    Cornucopia::Util::ReportTable.new(nested_table:         PseudoCleaner::MasterCleaner.report_table,
                                      nested_table_label:   description,
                                      suppress_blank_table: true) do |sub_report|
      @report_table = sub_report

      block.yield
    end
  else
    block.yield
  end

  @report_table = nil
end