A simple app for executing SQL queries in Django admin panel.

wat

def format_sql(query):
        keywords = ['select', 'from', 'as', 'join', 'left', 'on',
                    'where', 'and', 'case', 'else', 'end', 'is',
                    'null', 'union', 'order', 'by', 'concat',
                    'to_char', 'limit', 'or']
        new_query = []
        flag = False

        for word in query.split():
            if word in keywords:
                word = word.upper()

            word += ' '
            if '(' in word and ')' not in word:
                flag = True
                new_query.append(word)
                continue
            if flag and (')' not in word or '(' in word):
                new_query.append(word)
                continue
            else:
                flag = False

            if word.strip().endswith(','):
                word += '\n\t'
            if word.strip() == 'FROM':
                word = '\n' + word
            if word.strip() == 'WHERE':
                word = '\n' + word + '\n\t'
            if word.strip() in ('LEFT', 'AND'):
                word = '\n\t' + word
            if word.strip() == 'SELECT':
                word += '\n\t'
            if word.strip() in ('WHEN', 'ELSE', 'END'):
                word = '\n\t\t' + word

            new_query.append(word)

        return ''.join(new_query)
/r/django Thread Link - github.com