How to use the sqlparse.format function in sqlparse

To help you get started, we’ve selected a few sqlparse examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github andialbrecht / sqlparse / tests / test_format.py View on Github external
def test_duplicate_linebreaks(self):
        # issue3
        f = lambda sql: sqlparse.format(sql, reindent=True)
        s = 'select c1 -- column1\nfrom foo'
        assert f(s) == '\n'.join([
            'select c1 -- column1',
            'from foo'])
        s = 'select c1 -- column1\nfrom foo'
        r = sqlparse.format(s, reindent=True, strip_comments=True)
        assert r == '\n'.join([
            'select c1',
            'from foo'])
        s = 'select c1\nfrom foo\norder by c1'
        assert f(s) == '\n'.join([
            'select c1',
            'from foo',
            'order by c1'])
        s = 'select c1 from t1 where (c1 = 1) order by c1'
        assert f(s) == '\n'.join([
            'select c1',
            'from t1',
            'where (c1 = 1)',
            'order by c1'])
github CivicSpleen / ambry / test / functional / test_sql_parser.py View on Github external
INSTALL build.example.com-casters-simple;
INSTALL build.example.com-casters-simple_stats;
MATERIALIZE build.example.com-casters-integers;
MATERIALIZE build.example.com-casters-simple_stats;

SELECT t1.uuid AS t1_uuid, t2.float_a AS t2_float_a, t3.a AS t3_a
    FROM build.example.com-casters-simple AS t1
    JOIN build.example.com-casters-simple_stats AS t2 ON t1.id = t2.index
    JOIN build.example.com-casters-integers AS t3 ON t3_a = t2.index;


CREATE VIEW view1 AS SELECT col1 as c1, col2 as c2 FROM table1 WHERE foo is None and bar is baz;

"""
        statements = sqlparse.parse(sqlparse.format(sql, strip_comments=True))

        rec_keys = ['statement', 'install', 'materialize', 'tables',  'drop', 'indexes', 'joins']

        expected = [
            [u'INSTALL p00casters006003', set([u'p00casters006003']), None, None, None, None, None],
            [u'INSTALL p00casters002003', set([u'p00casters002003']), None, None, None, None, None],
            [u'MATERIALIZE p00casters004003', None, set([u'p00casters004003']), None, None, None, None],
            [u'MATERIALIZE p00casters002003', None, set([u'p00casters002003']), None, None, None, None],
            [u'SELECT t1.uuid AS t1_uuid, t2.float_a AS t2_float_a, t3.a AS t3_a FROM p00casters006003 AS t1 JOIN p00casters002003 AS t2 ON t1.id = t2.index JOIN p00casters004003 AS t3 ON t3_a = t2.index',
             None, set([u'p00casters004003', u'p00casters006003', u'p00casters002003']), None, None,
             set([(u'p00casters006003', (u'id',)), (u'p00casters002003', (u'index',))]), None],
            [u'CREATE VIEW view1 AS SELECT col1 as c1, col2 as c2 FROM table1 WHERE foo is None and bar is baz',
             None, None, None, ['DROP VIEW IF EXISTS view1;'], None, None],
            [None, None, None, None, None, None, None]
        ]
github andialbrecht / sqlparse / tests / test_format.py View on Github external
def test_identifiercase_quotes(self):
        sql = 'select * from "foo"."bar"'
        res = sqlparse.format(sql, identifier_case="upper")
        assert res == 'select * from "foo"."bar"'
github canningj / PiLapser / piENV / lib / python3.5 / site-packages / django / db / backends / base / operations.py View on Github external
try:
            # This import must stay inside the method because it's optional.
            import sqlparse
        except ImportError:
            if _allow_fallback:
                # Without sqlparse, fall back to the legacy (and buggy) logic.
                warnings.warn(
                    "Providing initial SQL data on a %s database will require "
                    "sqlparse in Django 1.9." % self.connection.vendor,
                    RemovedInDjango19Warning)
                from django.core.management.sql import _split_statements
                return _split_statements(sql)
            else:
                raise
        else:
            return [sqlparse.format(statement, strip_comments=True)
                    for statement in sqlparse.split(sql) if statement]
github django / django / django / db / backends / __init__.py View on Github external
try:
            # This import must stay inside the method because it's optional.
            import sqlparse
        except ImportError:
            if _allow_fallback:
                # Without sqlparse, fall back to the legacy (and buggy) logic.
                warnings.warn(
                    "Providing initial SQL data on a %s database will require "
                    "sqlparse in Django 1.9." % self.connection.vendor,
                    RemovedInDjango19Warning)
                from django.core.management.sql import _split_statements
                return _split_statements(sql)
            else:
                raise
        else:
            return [sqlparse.format(statement, strip_comments=True)
                    for statement in sqlparse.split(sql) if statement]
github hhyo / Archery / sql / utils / sql_utils.py View on Github external
:param text:
    :return: [{"sql_id": key, "sql": soar.compress(value)}]
    """
    # 尝试XML解析
    try:
        mapper, xml_raw_text = mybatis_mapper2sql.create_mapper(xml_raw_text=text)
        statements = mybatis_mapper2sql.get_statement(mapper, result_type='list')
        rows = []
        # 压缩SQL语句,方便展示
        for statement in statements:
            for key, value in statement.items():
                row = {"sql_id": key, "sql": value}
                rows.append(row)
    except xml.etree.ElementTree.ParseError:
        # 删除注释语句
        text = sqlparse.format(text, strip_comments=True)
        statements = sqlparse.split(text)
        rows = []
        num = 0
        for statement in statements:
            num = num + 1
            row = {"sql_id": num, "sql": statement}
            rows.append(row)
    return rows
github apache / incubator-superset / superset / db_engine_specs.py View on Github external
full_table_name = quote(schema) + '.' + quote(table_name)
        else:
            full_table_name = quote(table_name)

        qry = select(fields).select_from(text(full_table_name))

        if limit:
            qry = qry.limit(limit)
        if latest_partition:
            partition_query = cls.where_latest_partition(
                table_name, schema, my_db, qry, columns=cols)
            if partition_query != False:  # noqa
                qry = partition_query
        sql = my_db.compile_sqla_query(qry)
        if indent:
            sql = sqlparse.format(sql, reindent=True)
        return sql
github freewizard / SublimeFormatSQL / FormatSQL.py View on Github external
def _run(self, s):
        settings = self.view.settings()
        #indent_char = " " if settings.get("translate_tabs_to_spaces") else "\t"
        indent_char = " " #TODO indent by TAB (currently not supported in python-sqlparse)
        indent_size = int(settings.get("tab_size")) if indent_char == " " else 1
        s = s.encode("utf-8")
        return format(
            s, keyword_case="upper", reindent=True, indent_width=indent_size
        )
github zentralopensource / zentral / zentral / utils / sql.py View on Github external
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)
github apple / ccs-calendarserver / contrib / tools / pg_stats_analysis.py View on Github external
def sqlnormalize(sql):
    try:
        statements = sqlparse.parse(sql)
    except ValueError, e:
        print(e)
    # Replace any literal values with placeholders
    qmark = sqlparse.sql.Token('Operator', '?')
    _substitute(statements[0], qmark)
    return sqlparse.format(statements[0].to_unicode().encode('ascii'))