codekingpro/portable-devtools
115k
1#2# Copyright (C) 2009-2020 the sqlparse authors and contributors3# <see AUTHORS file>4#5# This module is part of python-sqlparse and is released under6# the BSD License: https://opensource.org/licenses/BSD-3-Clause7 8"""Parse SQL statements."""9 10# Setup namespace11from sqlparse import sql12from sqlparse import cli13from sqlparse import engine14from sqlparse import tokens15from sqlparse import filters16from sqlparse import formatter17 18 19__version__ = '0.5.0'20__all__ = ['engine', 'filters', 'formatter', 'sql', 'tokens', 'cli']21 22 23def parse(sql, encoding=None):24 """Parse sql and return a list of statements.25 26 :param sql: A string containing one or more SQL statements.27 :param encoding: The encoding of the statement (optional).28 :returns: A tuple of :class:`~sqlparse.sql.Statement` instances.29 """30 return tuple(parsestream(sql, encoding))31 32 33def parsestream(stream, encoding=None):34 """Parses sql statements from file-like object.35 36 :param stream: A file-like object.37 :param encoding: The encoding of the stream contents (optional).38 :returns: A generator of :class:`~sqlparse.sql.Statement` instances.39 """40 stack = engine.FilterStack()41 stack.enable_grouping()42 return stack.run(stream, encoding)43 44 45def format(sql, encoding=None, **options):46 """Format *sql* according to *options*.47 48 Available options are documented in :ref:`formatting`.49 50 In addition to the formatting options this function accepts the51 keyword "encoding" which determines the encoding of the statement.52 53 :returns: The formatted SQL statement as string.54 """55 stack = engine.FilterStack()56 options = formatter.validate_options(options)57 stack = formatter.build_filter_stack(stack, options)58 stack.postprocess.append(filters.SerializerUnicode())59 return ''.join(stack.run(sql, encoding))60 61 62def split(sql, encoding=None, strip_semicolon=False):63 """Split *sql* into single statements.64 65 :param sql: A string containing one or more SQL statements.66 :param encoding: The encoding of the statement (optional).67 :param strip_semicolon: If True, remove trainling semicolons68 (default: False).69 :returns: A list of strings.70 """71 stack = engine.FilterStack(strip_semicolon=strip_semicolon)72 return [str(stmt).strip() for stmt in stack.run(sql, encoding)]73 