Python pygments.lexers.SqlLexer() Examples

The following are 6 code examples of pygments.lexers.SqlLexer(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pygments.lexers , or try the search function .
Example #1
Source File: utils.py    From airflow with Apache License 2.0 5 votes vote down vote up
def get_attr_renderer():
    """Return Dictionary containing different Pygements Lexers for Rendering & Highlighting"""
    return {
        'bash_command': lambda x: render(x, lexers.BashLexer),
        'hql': lambda x: render(x, lexers.SqlLexer),
        'sql': lambda x: render(x, lexers.SqlLexer),
        'doc': lambda x: render(x, lexers.TextLexer),
        'doc_json': lambda x: render(x, lexers.JsonLexer),
        'doc_rst': lambda x: render(x, lexers.RstLexer),
        'doc_yaml': lambda x: render(x, lexers.YamlLexer),
        'doc_md': wrapped_markdown,
        'python_callable': lambda x: render(get_python_source(x), lexers.PythonLexer),
    } 
Example #2
Source File: sql.py    From zentral with Apache License 2.0 5 votes vote down vote up
def format_sql(query):
    if not query:
        return ""
    sql_lexer = SqlLexer()
    html_formatter = HtmlFormatter()
    reindent = len(query) > 80
    query = sqlparse.format(query, reindent=reindent, keyword_case='upper')
    return highlight(query, sql_lexer, html_formatter) 
Example #3
Source File: legacy.py    From codenn with MIT License 5 votes vote down vote up
def _format_sql(sql, data, format='html'):
    popts = {}
    if data.get('remove_comments'):
        popts['strip_comments'] = True
    if data.get('keyword_case', 'undefined') not in ('undefined', ''):
        popts['keyword_case'] = data.get('keyword_case')
    if data.get('identifier_case', 'undefined') not in ('undefined', ''):
        popts['identifier_case'] = data.get('identifier_case')
    if data.get('n_indents', None) is not None:
        val = data.get('n_indents')
        try:
            popts['indent_width'] = max(1, min(1000, int(val)))
            popts['reindent'] = True
        except (ValueError, TypeError):
            pass
    if (not 'indent_width' in popts and
        data.get('reindent', '').lower() in ('1', 'true', 't')):
        popts['indent_width'] = 2
        popts['reindent'] = True
    if data.get('output_format', None) is not None:
        popts['output_format'] = data.get('output_format')
    logging.debug('Format: %s, POPTS: %r', format, popts)
    logging.debug(sql)
    sql = sqlparse.format(sql, **popts)
    if format in ('html', 'json'):
        if data.get('highlight', False):
            if popts['output_format'] == 'python':
                lexer = PythonLexer()
            elif popts['output_format'] == 'php':
                lexer = PhpLexer()
            else:
                lexer = SqlLexer()
            sql = highlight(sql, lexer, HtmlFormatter())
        else:
            sql = ('<textarea class="resizable" '
                   'style="height: 350px; margin-top: 1em;">%s</textarea>'
                   % sql)
    return sql 
Example #4
Source File: crawl_patches.py    From vulncode-db with Apache License 2.0 5 votes vote down vote up
def dump_query(query, filter_columns=None):
    """
    Small helper function to dump a SqlAlchemy SQL query + parameters.
    :param query:
    :param filter_columns:
    :return:
    """
    # Number of rows to display.
    num_rows = 5

    if hasattr(query, "statement"):
        sql_query = str(
            query.statement.compile(dialect=None,
                                    compile_kwargs={"literal_binds": True}))
    else:
        sql_query = str(query)

    formatted_sql_query = sqlparse.format(sql_query,
                                          reindent=True,
                                          keyword_case="upper")
    highlighted_sql_query = highlight(formatted_sql_query, SqlLexer(),
                                      TerminalFormatter())
    print("Query:")
    print(f"{'-' * 15}\n{highlighted_sql_query}{'-' * 15}")

    df = pd.read_sql(query.statement, CVE_DB_ENGINE)
    if filter_columns:
        df = df[filter_columns]

    print(f"Results: {df.shape[0]}; showing first {num_rows}:")
    print(df.head(num_rows)) 
Example #5
Source File: sqlformatter.py    From sqlformatter with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.highlight = kwargs.pop('highlight', True)
        self.style = kwargs.pop('style', 'default')

        self.parse = kwargs.pop('parse', True)
        self.reindent = kwargs.pop('reindent', True)
        self.keyword_case = kwargs.pop('keyword_case', 'upper')

        self._lexer = SqlLexer()
        self._formatter = Terminal256Formatter(style=self.style)

        super(SqlFormatter, self).__init__(*args, **kwargs) 
Example #6
Source File: console.py    From gsheets-db-api with MIT License 4 votes vote down vote up
def main():
    history = FileHistory(os.path.expanduser('~/.gsheetsdb_history'))

    arguments = docopt(__doc__, version=__version__.__version__)

    auth = {
        'service_account_file': arguments['--service-account-file'],
        'subject': arguments['--subject'],
    }
    credentials = get_credentials_from_auth(**auth)
    connection = connect(credentials)
    headers = int(arguments['--headers'])
    cursor = connection.cursor()

    lexer = PygmentsLexer(SqlLexer)
    words = keywords + aggregate_functions + scalar_functions
    completer = WordCompleter(words, ignore_case=True)
    style = style_from_pygments_cls(get_style_by_name('manni'))

    while True:
        try:
            query = prompt(
                'sql> ', lexer=lexer, completer=completer,
                style=style, history=history)
        except (EOFError, KeyboardInterrupt):
            break  # Control-D pressed.

        # run query
        query = query.strip('; ').replace('%', '%%')
        if query:
            try:
                result = cursor.execute(query, headers=headers)
            except Exception as e:
                if arguments['--raise']:
                    raise
                print(e)
                continue

            columns = [t[0] for t in cursor.description or []]
            print(tabulate(result, headers=columns))

    print('See ya!')