class Mysqlman::Privs

Public Class Methods

new(user) click to toggle source
# File lib/mysqlman/privs.rb, line 10
def initialize(user)
  @user = user
  @conn = Connection.instance
  @logger = Logger.new(STDOUT)
end

Public Instance Methods

fetch() click to toggle source
# File lib/mysqlman/privs.rb, line 16
def fetch
  reload_privs
end

Private Instance Methods

add_grantable(privs) click to toggle source
# File lib/mysqlman/privs.rb, line 70
def add_grantable(privs)
  privs.uniq { |priv| [priv[:schema], priv[:table]] }.each do |names|
    is_grant = grantable_collection?(privs, names)
    next unless is_grant
    privs.push(
      schema: names[:schema], table: names[:table], type: 'GRANT OPTION'
    )
  end
  privs
end
fetch_privs(table, columns) click to toggle source
# File lib/mysqlman/privs.rb, line 50
def fetch_privs(table, columns)
  @conn.query(fetch_query(table, columns)).map do |row|
    {
      schema: row['TABLE_SCHEMA'],
      table: row['TABLE_NAME'],
      type: row['PRIVILEGE_TYPE'],
      grant: row['IS_GRANTABLE'] == 'YES'
    }
  end
end
fetch_query(table, columns) click to toggle source
# File lib/mysqlman/privs.rb, line 61
    def fetch_query(table, columns)
      <<-SQL
        SELECT #{columns.join(',')}
        FROM #{table}
        WHERE
          GRANTEE = '\\\'#{@user.user}\\\'@\\\'#{@user.host}\\\''
      SQL
    end
format_privs(privs) click to toggle source
# File lib/mysqlman/privs.rb, line 88
def format_privs(privs)
  privs.reject { |p| p[:type] == 'USAGE' }.map do |priv|
    priv.delete(:grant)
    priv
  end
end
global_privs() click to toggle source
# File lib/mysqlman/privs.rb, line 26
def global_privs
  privs = fetch_privs(
    'information_schema.USER_PRIVILEGES',
    %w[PRIVILEGE_TYPE IS_GRANTABLE]
  )
  format_privs(add_grantable(privs))
end
grantable_collection?(privs, names) click to toggle source
# File lib/mysqlman/privs.rb, line 81
def grantable_collection?(privs, names)
  collection = privs.select do |priv|
    priv[:schema] == names[:schema] && priv[:table] == names[:table]
  end
  collection.all? { |priv| priv[:grant] }
end
reload_privs() click to toggle source
# File lib/mysqlman/privs.rb, line 22
def reload_privs
  [global_privs, schema_privs, table_privs].compact.flatten
end
schema_privs() click to toggle source
# File lib/mysqlman/privs.rb, line 34
def schema_privs
  privs = fetch_privs(
    'information_schema.SCHEMA_PRIVILEGES',
    %w[TABLE_SCHEMA PRIVILEGE_TYPE IS_GRANTABLE]
  )
  format_privs(add_grantable(privs))
end
table_privs() click to toggle source
# File lib/mysqlman/privs.rb, line 42
def table_privs
  privs = fetch_privs(
    'information_schema.TABLE_PRIVILEGES',
    %w[TABLE_NAME TABLE_SCHEMA PRIVILEGE_TYPE IS_GRANTABLE]
  )
  format_privs(add_grantable(privs))
end