Module: DatabaseCleaner::ActiveRecord::SelectiveTruncation

Included in:
Deletion
Defined in:
lib/database_cleaner/active_record/deletion.rb

Instance Method Summary collapse

Instance Method Details

#information_schema_exists?(connection) ⇒ Boolean

Returns:

  • (Boolean)


82
83
84
85
86
87
88
89
90
91
# File 'lib/database_cleaner/active_record/deletion.rb', line 82

def information_schema_exists? connection
  return false unless connection.is_a? ActiveRecord::ConnectionAdapters::Mysql2Adapter
  @information_schema_exists ||=
    begin
      connection.execute("SELECT 1 FROM information_schema.tables")
      true
    rescue
      false
    end
end

#table_stats_query(connection, db_name) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/database_cleaner/active_record/deletion.rb', line 65

def table_stats_query(connection, db_name)
  if @cache_tables && !@table_stats_query.nil?
    return @table_stats_query
  else
    tables = connection.select_values(<<-SQL)
      SELECT table_name
      FROM information_schema.tables
      WHERE table_schema = '#{db_name}'
      AND #{::DatabaseCleaner::ActiveRecord::Base.exclusion_condition('table_name')};
    SQL
    queries = tables.map do |table|
      "SELECT #{connection.quote(table)} AS table_name, COUNT(*) AS exact_row_count FROM #{connection.quote_table_name(table)}"
    end
    @table_stats_query = queries.join(' UNION ')
  end
end

#tables_to_truncate(connection) ⇒ Object



47
48
49
50
51
52
53
# File 'lib/database_cleaner/active_record/deletion.rb', line 47

def tables_to_truncate(connection)
  if information_schema_exists?(connection)
    (@only || tables_with_new_rows(connection)) - @tables_to_exclude
  else
    super
  end
end

#tables_with_new_rows(connection) ⇒ Object



55
56
57
58
59
60
61
62
63
# File 'lib/database_cleaner/active_record/deletion.rb', line 55

def tables_with_new_rows(connection)
  @db_name ||= connection.instance_variable_get('@config')[:database]
  stats = table_stats_query(connection, @db_name)
  if stats != ''
    connection.exec_query(stats).inject([]) {|all, stat| all << stat['table_name'] if stat['exact_row_count'] > 0; all }
  else
    []
  end
end