def get_variables(cnx, pattern=None, variables=None, global_vars=False):
    """Get session or global system variables

    We use the MySQL connection cnx to query the INFORMATION_SCHEMA
    table SESSION_VARIABLES or, when global_vars is True, the table
    GLOBAL_VARIABLES.

    :param cnx: Valid MySQL connection
    :param pattern: Pattern to use (used for LIKE)
    :param variables: Variables to query for
    :return: Dictionary containing variables with values or empty dict
    :rtype : dict
    """

    format_vars = {
        'where_clause': '',
        'where': '',
    }
    ver = cnx.get_server_version()
    if ver >= (5, 7, 6):
        table_global_vars = 'global_variables'
        table_session_vars = 'session_variables'
        format_vars['schema'] = 'performance_schema'
    else:
        table_global_vars = 'GLOBAL_VARIABLES'
        table_session_vars = 'SESSION_VARIABLES'
        format_vars['schema'] = 'INFORMATION_SCHEMA'

    if global_vars is True:
        format_vars['table'] = table_global_vars
    else:
        format_vars['table'] = table_session_vars

    query = "SELECT * FROM {schema}.{table} {where} {where_clause}"

    where = []
    if pattern:
        where.append('VARIABLE_NAME LIKE "{0}"'.format(pattern))
    if variables:
        where.append('VARIABLE_NAME IN ({0})'.format(
            ','.join([ "'{0}'".format(name) for name in variables ])
        ))

    if where:
        format_vars['where'] = 'WHERE'
        format_vars['where_clause'] = ' OR '.join(where)

    cnx.query(query.format(**format_vars))
    result = {}

    row = cnx.fetch_row()
    while row:
        result[row[0].lower()] = row[1]
        row = cnx.fetch_row()

    cnx.free_result()
    return result