本文整理匯總了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,))
示例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
示例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
示例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
示例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
示例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)
示例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]
示例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
示例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)
示例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]
示例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)')
示例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")
示例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']
))
示例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']))
示例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