当前位置: 首页>>代码示例>>Python>>正文


Python sqlparse.format方法代码示例

本文整理汇总了Python中sqlparse.format方法的典型用法代码示例。如果您正苦于以下问题:Python sqlparse.format方法的具体用法?Python sqlparse.format怎么用?Python sqlparse.format使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sqlparse的用法示例。


在下文中一共展示了sqlparse.format方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: view_definition

# 需要导入模块: import sqlparse [as 别名]
# 或者: from sqlparse import format [as 别名]
def view_definition(self, spec):
        """Returns the SQL defining views described by `spec`"""

        template = "CREATE OR REPLACE {6} VIEW {0}.{1} AS \n{3}"
        # 2: relkind, v or m (materialized)
        # 4: reloptions, null
        # 5: checkoption: local or cascaded
        with self.conn.cursor() as cur:
            sql = self.view_definition_query
            _logger.debug("View Definition Query. sql: %r\nspec: %r", sql, spec)
            try:
                cur.execute(sql, (spec,))
            except psycopg2.ProgrammingError:
                raise RuntimeError("View {} does not exist.".format(spec))
            result = cur.fetchone()
            view_type = "MATERIALIZED" if result[2] == "m" else ""
            return template.format(*result + (view_type,)) 
开发者ID:dbcli,项目名称:pgcli,代码行数:19,代码来源:pgexecute.py

示例2: statement_cleanup

# 需要导入模块: import sqlparse [as 别名]
# 或者: from sqlparse import format [as 别名]
def statement_cleanup(cls, statement):
        """
        Clean up statements prior to hash computation.

        This classmethod takes an SQL statement and reformats it by consistently
        removing comments and replacing all whitespace. It is used by the
        `statement_hash` method to avoid functionally identical queries hitting
        different cache keys. If the statement's language is not to be SQL, this
        method should be overloaded appropriately.

        Args:
            statement (str): The statement to be reformatted/cleaned-up.

        Returns:
            str: The new statement, consistently reformatted.
        """
        statement = sqlparse.format(statement, strip_comments=True, reindent=True)
        statement = os.linesep.join([line for line in statement.splitlines() if line])
        return statement 
开发者ID:airbnb,项目名称:omniduct,代码行数:21,代码来源:base.py

示例3: _get_statements

# 需要导入模块: import sqlparse [as 别名]
# 或者: from sqlparse import format [as 别名]
def _get_statements(path):
    """
    Get statements from file
    """
    with codecs.open(path, encoding='utf-8') as i:
        data = i.read()
    if u'/* pgmigrate-encoding: utf-8 */' not in data:
        try:
            data.encode('ascii')
        except UnicodeError as exc:
            raise MalformedStatement(
                'Non ascii symbols in file: {0}, {1}'.format(path, text(exc)))
    data = sqlparse.format(data, strip_comments=True)
    for statement in sqlparse.parsestream(data, encoding='utf-8'):
        st_str = text(statement).strip().encode('utf-8')
        if st_str:
            yield st_str 
开发者ID:yandex,项目名称:pgmigrate,代码行数:19,代码来源:pgmigrate.py

示例4: _parse_str_callbacks

# 需要导入模块: import sqlparse [as 别名]
# 或者: from sqlparse import format [as 别名]
def _parse_str_callbacks(callbacks, ret, base_dir):
    callbacks = callbacks.split(',')
    for callback in callbacks:
        if not callback:
            continue
        tokens = callback.split(':')
        if tokens[0] not in ret._fields:
            raise ConfigurationError(
                'Unexpected callback '
                'type: {type}'.format(type=text(tokens[0])))
        path = os.path.join(base_dir, tokens[1])
        if not os.path.exists(path):
            raise ConfigurationError(
                'Path unavailable: {path}'.format(path=text(path)))
        if os.path.isdir(path):
            for fname in sorted(os.listdir(path)):
                getattr(ret, tokens[0]).append(os.path.join(path, fname))
        else:
            getattr(ret, tokens[0]).append(path)

    return ret 
开发者ID:yandex,项目名称:pgmigrate,代码行数:23,代码来源:pgmigrate.py

示例5: _parse_dict_callbacks

# 需要导入模块: import sqlparse [as 别名]
# 或者: from sqlparse import format [as 别名]
def _parse_dict_callbacks(callbacks, ret, base_dir):
    for i in callbacks:
        if i in ret._fields:
            for j in callbacks[i]:
                path = os.path.join(base_dir, j)
                if not os.path.exists(path):
                    raise ConfigurationError(
                        'Path unavailable: {path}'.format(path=text(path)))
                if os.path.isdir(path):
                    for fname in sorted(os.listdir(path)):
                        getattr(ret, i).append(os.path.join(path, fname))
                else:
                    getattr(ret, i).append(path)
        else:
            raise ConfigurationError(
                'Unexpected callback type: {type}'.format(type=text(i)))

    return ret 
开发者ID:yandex,项目名称:pgmigrate,代码行数:20,代码来源:pgmigrate.py

示例6: clean

# 需要导入模块: import sqlparse [as 别名]
# 或者: from sqlparse import format [as 别名]
def clean(config):
    """
    Drop schema_version table
    """
    if _is_initialized(config.schema, config.cursor):
        LOG.info('dropping schema_version')
        config.cursor.execute(
            SQL('DROP TABLE {schema}.schema_version').format(
                schema=Identifier(config.schema)))
        LOG.info(config.cursor.statusmessage)
        LOG.info('dropping schema_version_type')
        config.cursor.execute(
            SQL('DROP TYPE {schema}.schema_version_type').format(
                schema=Identifier(config.schema)))
        LOG.info(config.cursor.statusmessage)
        _finish(config) 
开发者ID:yandex,项目名称:pgmigrate,代码行数:18,代码来源:pgmigrate.py

示例7: prepare_sql_script

# 需要导入模块: import sqlparse [as 别名]
# 或者: from sqlparse import format [as 别名]
def prepare_sql_script(self, sql):
        """
        Take an SQL script that may contain multiple lines and return a list
        of statements to feed to successive cursor.execute() calls.

        Since few databases are able to process raw SQL scripts in a single
        cursor.execute() call and PEP 249 doesn't talk about this use case,
        the default implementation is conservative.
        """
        try:
            import sqlparse
        except ImportError:
            raise ImproperlyConfigured(
                "sqlparse is required if you don't split your SQL "
                "statements manually."
            )
        else:
            return [sqlparse.format(statement, strip_comments=True)
                    for statement in sqlparse.split(sql) if statement] 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:21,代码来源:operations.py

示例8: postprocess_one

# 需要导入模块: import sqlparse [as 别名]
# 或者: from sqlparse import format [as 别名]
def postprocess_one(pred_sql, schema):
  pred_sql = pred_sql.replace('group_by', 'group by').replace('order_by', 'order by').replace('limit_value', 'limit 1').replace('_EOS', '').replace(' value ',' 1 ').replace('distinct', '').strip(',').strip()
  if pred_sql.endswith('value'):
    pred_sql = pred_sql[:-len('value')] + '1'

  try:
    format_sql = sqlparse.format(pred_sql, reindent=True)
  except:
    return pred_sql
  format_sql_2 = normalize_space(format_sql)

  num_select = format_sql_2.count('select')

  if num_select > 1:
    final_sql = postprocess_nested(format_sql_2, schema)
  else:
    final_sql, _ = postprocess_single(format_sql_2, schema)

  return final_sql 
开发者ID:ryanzhumich,项目名称:editsql,代码行数:21,代码来源:postprocess_eval.py

示例9: get_child_statement

# 需要导入模块: import sqlparse [as 别名]
# 或者: from sqlparse import format [as 别名]
def get_child_statement(mybatis_mapper, child_id, **kwargs):
    """
    Get SQL Statement By child_id
    Formatting of SQL Statements
    :return:
    """
    # format kwargs
    kwargs = kwargs if kwargs else {'reindent': True, 'strip_comments': True}
    # get sql
    statement = ''
    child = mybatis_mapper.get(child_id)
    statement += convert_children(mybatis_mapper, child, **kwargs)
    # The child element has children
    for next_child in child:
        statement += convert_children(mybatis_mapper, next_child, **kwargs)
    return sqlparse.format(statement, **kwargs) 
开发者ID:hhyo,项目名称:mybatis-mapper2sql,代码行数:18,代码来源:generate.py

示例10: prepare_sql_script

# 需要导入模块: import sqlparse [as 别名]
# 或者: from sqlparse import format [as 别名]
def prepare_sql_script(self, sql):
        """
        Take an SQL script that may contain multiple lines and return a list
        of statements to feed to successive cursor.execute() calls.

        Since few databases are able to process raw SQL scripts in a single
        cursor.execute() call and PEP 249 doesn't talk about this use case,
        the default implementation is conservative.
        """
        try:
            import sqlparse
        except ImportError:
            raise ImproperlyConfigured(
                "The sqlparse package is required if you don't split your SQL "
                "statements manually."
            )
        else:
            return [sqlparse.format(statement, strip_comments=True)
                    for statement in sqlparse.split(sql) if statement] 
开发者ID:PacktPublishing,项目名称:Hands-On-Application-Development-with-PyCharm,代码行数:21,代码来源:operations.py

示例11: test_strip_comments_multi

# 需要导入模块: import sqlparse [as 别名]
# 或者: from sqlparse import format [as 别名]
def test_strip_comments_multi(self):
        sql = '/* sql starts here */\nselect'
        res = sqlparse.format(sql, strip_comments=True)
        self.ndiffAssertEqual(res, 'select')
        sql = '/* sql starts here */ select'
        res = sqlparse.format(sql, strip_comments=True)
        self.ndiffAssertEqual(res, 'select')
        sql = '/*\n * sql starts here\n */\nselect'
        res = sqlparse.format(sql, strip_comments=True)
        self.ndiffAssertEqual(res, 'select')
        sql = 'select (/* sql starts here */ select 2)'
        res = sqlparse.format(sql, strip_comments=True)
        self.ndiffAssertEqual(res, 'select (select 2)')
        sql = 'select (/* sql /* starts here */ select 2)'
        res = sqlparse.format(sql, strip_comments=True)
        self.ndiffAssertEqual(res, 'select (select 2)') 
开发者ID:sriniiyer,项目名称:codenn,代码行数:18,代码来源:test_format.py

示例12: test_notransform_of_quoted_crlf

# 需要导入模块: import sqlparse [as 别名]
# 或者: from sqlparse import format [as 别名]
def test_notransform_of_quoted_crlf(self):
        # Make sure that CR/CR+LF characters inside string literals don't get
        # affected by the formatter.

        s1 = "SELECT some_column LIKE 'value\r'"
        s2 = "SELECT some_column LIKE 'value\r'\r\nWHERE id = 1\n"
        s3 = "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\r"
        s4 = "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\r\n"

        f = lambda x: sqlparse.format(x)

        # Because of the use of
        self.ndiffAssertEqual(f(s1), "SELECT some_column LIKE 'value\r'")
        self.ndiffAssertEqual(f(s2), "SELECT some_column LIKE 'value\r'\nWHERE id = 1\n")
        self.ndiffAssertEqual(f(s3), "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\n")
        self.ndiffAssertEqual(f(s4), "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\n") 
开发者ID:sriniiyer,项目名称:codenn,代码行数:18,代码来源:test_format.py

示例13: test_join

# 需要导入模块: import sqlparse [as 别名]
# 或者: from sqlparse import format [as 别名]
def test_join(self):
        f = lambda sql: sqlparse.format(sql, reindent=True)
        s = 'select * from foo join bar on 1 = 2'
        self.ndiffAssertEqual(f(s), '\n'.join(['select *',
                                               'from foo',
                                               'join bar on 1 = 2']))
        s = 'select * from foo inner join bar on 1 = 2'
        self.ndiffAssertEqual(f(s), '\n'.join(['select *',
                                               'from foo',
                                               'inner join bar on 1 = 2']))
        s = 'select * from foo left outer join bar on 1 = 2'
        self.ndiffAssertEqual(f(s), '\n'.join(['select *',
                                               'from foo',
                                               'left outer join bar on 1 = 2']
                                              ))
        s = 'select * from foo straight_join bar on 1 = 2'
        self.ndiffAssertEqual(f(s), '\n'.join(['select *',
                                               'from foo',
                                               'straight_join bar on 1 = 2']
                                              )) 
开发者ID:sriniiyer,项目名称:codenn,代码行数:22,代码来源:test_format.py

示例14: test_duplicate_linebreaks

# 需要导入模块: import sqlparse [as 别名]
# 或者: from sqlparse import format [as 别名]
def test_duplicate_linebreaks(self):  # issue3
        f = lambda sql: sqlparse.format(sql, reindent=True)
        s = 'select c1 -- column1\nfrom foo'
        self.ndiffAssertEqual(f(s), '\n'.join(['select c1 -- column1',
                                               'from foo']))
        s = 'select c1 -- column1\nfrom foo'
        r = sqlparse.format(s, reindent=True, strip_comments=True)
        self.ndiffAssertEqual(r, '\n'.join(['select c1',
                                            'from foo']))
        s = 'select c1\nfrom foo\norder by c1'
        self.ndiffAssertEqual(f(s), '\n'.join(['select c1',
                                               'from foo',
                                               'order by c1']))
        s = 'select c1 from t1 where (c1 = 1) order by c1'
        self.ndiffAssertEqual(f(s), '\n'.join(['select c1',
                                               'from t1',
                                               'where (c1 = 1)',
                                               'order by c1'])) 
开发者ID:sriniiyer,项目名称:codenn,代码行数:20,代码来源:test_format.py

示例15: test_issue90

# 需要导入模块: import sqlparse [as 别名]
# 或者: from sqlparse import format [as 别名]
def test_issue90():
    sql = ('UPDATE "gallery_photo" SET "owner_id" = 4018, "deleted_at" = NULL,'
           ' "width" = NULL, "height" = NULL, "rating_votes" = 0,'
           ' "rating_score" = 0, "thumbnail_width" = NULL,'
           ' "thumbnail_height" = NULL, "price" = 1, "description" = NULL')
    formatted = sqlparse.format(sql, reindent=True)
    tformatted = '\n'.join(['UPDATE "gallery_photo"',
                            'SET "owner_id" = 4018,',
                            '    "deleted_at" = NULL,',
                            '    "width" = NULL,',
                            '    "height" = NULL,',
                            '    "rating_votes" = 0,',
                            '    "rating_score" = 0,',
                            '    "thumbnail_width" = NULL,',
                            '    "thumbnail_height" = NULL,',
                            '    "price" = 1,',
                            '    "description" = NULL'])
    assert formatted == tformatted 
开发者ID:sriniiyer,项目名称:codenn,代码行数:20,代码来源:test_regressions.py


注:本文中的sqlparse.format方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。