import re


def clean_variable_name(var_name):
    """Clean a single variable name ready for DB storage.

    Args:
        var_name (str): Variable name to be cleaned
    Returns:
        new_var_name (str): A MySQL compliant variable name.
    """

    # Lower, replace '%', remove non-alphanums and use '_'
    new_var_name = var_name.lower().replace("%", "pc")
    new_var_name = re.sub('[^0-9a-zA-Z]+', ' ', new_var_name)
    new_var_name = new_var_name.lstrip().rstrip().replace(" ", "_")
    # Recursively shorten from middle character until less than 64 chars long
    # (this is the default MySQL limit)
    # Middle character has been chosen to allow some readability.
    while len(new_var_name) > 64:
        # Find the longest term
        longest_term = ""
        for term in new_var_name.split("_"):
            if len(term) <= len(longest_term):
                continue
            longest_term = term
        # Remove the middle character from the longest term
        middle = len(longest_term) - 1
        new_term = longest_term[:middle] + longest_term[middle+1:]
        new_var_name = new_var_name.replace(longest_term, new_term)
    return new_var_name