Sha256: b50b455cf1cfd0fc29845080972c989249a3e8393597d56811f2e9aad0c790bd

Contents?: true

Size: 1.18 KB

Versions: 3

Compression:

Stored size: 1.18 KB

Contents

# Copyright (c) 2011, SoundCloud Ltd., Rany Keddo, Tobias Bielohlawek, Tobias
# Schmidt

module Lhm
  module SqlHelper
    extend self

    def idx_name(table_name, cols)
      column_names = column_definition(cols).map(&:first)
      "index_#{ table_name }_on_#{ column_names.join("_and_") }"
    end

    def idx_spec(cols)
      column_definition(cols).map do |name, length|
        "`#{name}`#{length}"
      end.join(', ')
    end

    def table?(table_name)
      connection.table_exists?(table_name)
    end

    def sql(statements)
      [statements].flatten.each do |statement|
        connection.execute(tagged(statement))
      end
    rescue ActiveRecord::StatementInvalid, Mysql::Error => e
      error e.message
    end

    def update(statements)
      [statements].flatten.inject(0) do |memo, statement|
        memo += connection.update(tagged(statement))
      end
    rescue ActiveRecord::StatementInvalid, Mysql::Error => e
      error e.message
    end

  private

    def tagged(statement)
      statement + " -- lhm"
    end

    def column_definition(cols)
      Array(cols).map do |column|
        column.to_s.match(/`?([^\(]+)`?(\([^\)]+\))?/).captures
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
lhm-1.0.0.rc6 lib/lhm/sql_helper.rb
lhm-1.0.0.rc5 lib/lhm/sql_helper.rb
lhm-1.0.0.rc4 lib/lhm/sql_helper.rb