Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/sqlparse/__init__.py: 68%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

22 statements  

1# 

2# Copyright (C) 2009-2020 the sqlparse authors and contributors 

3# <see AUTHORS file> 

4# 

5# This module is part of python-sqlparse and is released under 

6# the BSD License: https://opensource.org/licenses/BSD-3-Clause 

7 

8"""Parse SQL statements.""" 

9 

10# Setup namespace 

11from collections.abc import Generator 

12from typing import IO, Any 

13 

14from sqlparse import cli, engine, filters, formatter, sql, tokens 

15 

16__version__ = "0.5.6.dev0" 

17__all__ = ["cli", "engine", "filters", "formatter", "sql", "tokens"] 

18 

19 

20def parse( 

21 sql: str, encoding: str | None = None 

22) -> tuple[sql.Statement, ...]: 

23 """Parse sql and return a list of statements. 

24 

25 :param sql: A string containing one or more SQL statements. 

26 :param encoding: The encoding of the statement (optional). 

27 :returns: A tuple of :class:`~sqlparse.sql.Statement` instances. 

28 """ 

29 return tuple(parsestream(sql, encoding)) 

30 

31 

32def parsestream( 

33 stream: str | IO[str], encoding: str | None = None 

34) -> Generator[sql.Statement, None, None]: 

35 """Parses sql statements from file-like object. 

36 

37 :param stream: A file-like object. 

38 :param encoding: The encoding of the stream contents (optional). 

39 :returns: A generator of :class:`~sqlparse.sql.Statement` instances. 

40 """ 

41 stack = engine.FilterStack() 

42 stack.enable_grouping() 

43 return stack.run(stream, encoding) 

44 

45 

46def format(sql: str, encoding: str | None = None, **options: Any) -> str: 

47 """Format *sql* according to *options*. 

48 

49 Available options are documented in :ref:`formatting`. 

50 

51 In addition to the formatting options this function accepts the 

52 keyword "encoding" which determines the encoding of the statement. 

53 

54 :returns: The formatted SQL statement as string. 

55 """ 

56 stack = engine.FilterStack() 

57 options = formatter.validate_options(options) 

58 stack = formatter.build_filter_stack(stack, options) 

59 stack.postprocess.append(filters.SerializerUnicode()) 

60 return "".join(stack.run(sql, encoding)) 

61 

62 

63def split( 

64 sql: str, encoding: str | None = None, strip_semicolon: bool = False 

65) -> list[str]: 

66 """Split *sql* into single statements. 

67 

68 :param sql: A string containing one or more SQL statements. 

69 :param encoding: The encoding of the statement (optional). 

70 :param strip_semicolon: If True, remove trailing semicolons 

71 (default: False). 

72 :returns: A list of strings. 

73 """ 

74 stack = engine.FilterStack(strip_semicolon=strip_semicolon) 

75 return [str(stmt).strip() for stmt in stack.run(sql, encoding)]