Sha256: dad005519761afb6ebc254fa1cf9c38e4a791cdcde80193cc2eedf87fd418f01

Contents?: true

Size: 1.27 KB

Versions: 5

Compression:

Stored size: 1.27 KB

Contents

module AbAdmin
  module Utils
    module Mysql
      def self.included(base)
        base.extend(ClassMethods)
      end

      module ClassMethods
        # Deletes all rows in table very fast, but without calling +destroy+ method
        # nor any hooks.
        def truncate!
          transaction { connection.execute("TRUNCATE TABLE #{quoted_table_name};") }
        end

        # remove duplicate records by columns
        def remove_duplicates(*cols)
          conds = cols.map { |col| "#{table_name}.#{col} IS NOT NULL AND #{table_name}.#{col} = t.#{col}" }.join(' AND ')
          query = <<-SQL
            DELETE FROM #{table_name} USING #{table_name}, #{table_name} AS t WHERE #{table_name}.id < t.id AND #{conds}
          SQL
          connection.execute(query)
        end


        # Disables key updates for model table
        def disable_keys
          connection.execute("ALTER TABLE #{quoted_table_name} DISABLE KEYS")
        end

        # Enables key updates for model table
        def enable_keys
          connection.execute("ALTER TABLE #{quoted_table_name} ENABLE KEYS")
        end

        # Disables keys, yields block, enables keys.
        def with_keys_disabled
          disable_keys
          yield
          enable_keys
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
ab_admin-0.7.0 lib/ab_admin/utils/mysql.rb
ab_admin-0.6.1 lib/ab_admin/utils/mysql.rb
ab_admin-0.6.0 lib/ab_admin/utils/mysql.rb
ab_admin-0.5.0 lib/ab_admin/utils/mysql.rb
ab_admin-0.4.0 lib/ab_admin/utils/mysql.rb