Sha256: f8f9416199a185d0ed8c7db283d6d1f95be611a91ae924475f84f9623ee3f2db

Contents?: true

Size: 1.32 KB

Versions: 2

Compression:

Stored size: 1.32 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, deleted_id_order: '<')
          condition_sql = 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 #{deleted_id_order} t.id AND #{condition_sql}
          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

2 entries across 2 versions & 1 rubygems

Version Path
ab_admin-0.11.0 lib/ab_admin/utils/mysql.rb
ab_admin-0.10.0 lib/ab_admin/utils/mysql.rb