rsqlparse 0.1.0__cp39-abi3-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
rsqlparse/__init__.py ADDED
@@ -0,0 +1,145 @@
1
+ """Blazing-fast, zero-dependency, ReDoS-immune O(n) Rust drop-in replacement for sqlparse."""
2
+
3
+ from typing import IO, Any, Generator, List, Optional, Tuple, Union
4
+
5
+ from rsqlparse import cli, engine, exceptions, filters, formatter, keywords, lexer, sql, tokens
6
+ from rsqlparse._core import format_py, parse_py, split_py
7
+ from rsqlparse.lexer import Lexer, decode_input
8
+ from rsqlparse.sql import GROUP_CLASSES_BY_ID, _make_token_fast
9
+ from rsqlparse.tokens import TOKEN_TYPES_BY_ID
10
+
11
+ __version__ = "0.1.0"
12
+ __all__ = [
13
+ "cli",
14
+ "engine",
15
+ "exceptions",
16
+ "filters",
17
+ "formatter",
18
+ "keywords",
19
+ "lexer",
20
+ "sql",
21
+ "tokens",
22
+ "parse",
23
+ "parsestream",
24
+ "format",
25
+ "split",
26
+ ]
27
+
28
+
29
+ def _can_use_rust_fast_path() -> bool:
30
+ inst = Lexer._default_instance
31
+ return inst is None or inst._use_rust_fast_path
32
+
33
+
34
+ def parse(
35
+ sql_text: Union[str, bytes, IO[str]], encoding: Optional[str] = None
36
+ ) -> Tuple[sql.Statement, ...]:
37
+ """Parse sql and return a tuple of statements.
38
+
39
+ :param sql_text: A string, bytes, or file-like object containing SQL statements.
40
+ :param encoding: The encoding of the statement (optional).
41
+ :returns: A tuple of :class:`~rsqlparse.sql.Statement` instances.
42
+ """
43
+ if _can_use_rust_fast_path():
44
+ decoded = decode_input(sql_text, encoding)
45
+ return parse_py(
46
+ decoded,
47
+ TOKEN_TYPES_BY_ID,
48
+ _make_token_fast,
49
+ GROUP_CLASSES_BY_ID,
50
+ engine.grouping.MAX_GROUPING_DEPTH,
51
+ engine.grouping.MAX_GROUPING_TOKENS,
52
+ )
53
+ return tuple(parsestream(sql_text, encoding))
54
+
55
+
56
+ def parsestream(
57
+ stream: Union[str, bytes, IO[str]], encoding: Optional[str] = None
58
+ ) -> Generator[sql.Statement, None, None]:
59
+ """Parse sql statements from a string or file-like object.
60
+
61
+ :param stream: A string, bytes, or file-like object.
62
+ :param encoding: The encoding of the stream contents (optional).
63
+ :returns: A generator of :class:`~rsqlparse.sql.Statement` instances.
64
+ """
65
+ if _can_use_rust_fast_path():
66
+ decoded = decode_input(stream, encoding)
67
+ stmts = parse_py(
68
+ decoded,
69
+ TOKEN_TYPES_BY_ID,
70
+ _make_token_fast,
71
+ GROUP_CLASSES_BY_ID,
72
+ engine.grouping.MAX_GROUPING_DEPTH,
73
+ engine.grouping.MAX_GROUPING_TOKENS,
74
+ )
75
+ return (stmt for stmt in stmts)
76
+
77
+ stack = engine.FilterStack()
78
+ stack.enable_grouping()
79
+ return stack.run(stream, encoding)
80
+
81
+
82
+ def format(
83
+ sql_text: Union[str, bytes, IO[str]],
84
+ encoding: Optional[str] = None,
85
+ **options: Any,
86
+ ) -> str:
87
+ """Format *sql_text* according to *options*.
88
+
89
+ :returns: The formatted SQL statement as string.
90
+ """
91
+ validated = formatter.validate_options(dict(options))
92
+ if validated.get("right_margin"):
93
+ raise NotImplementedError
94
+
95
+ if _can_use_rust_fast_path():
96
+ decoded = decode_input(sql_text, encoding)
97
+ return format_py(
98
+ decoded,
99
+ keyword_case=validated.get("keyword_case"),
100
+ identifier_case=validated.get("identifier_case"),
101
+ output_format=validated.get("output_format"),
102
+ strip_comments=bool(validated.get("strip_comments", False)),
103
+ use_space_around_operators=bool(
104
+ validated.get("use_space_around_operators", False)
105
+ ),
106
+ strip_whitespace=bool(validated.get("strip_whitespace", False)),
107
+ truncate_strings=validated.get("truncate_strings"),
108
+ truncate_char=validated.get("truncate_char", "[...]"),
109
+ reindent=bool(validated.get("reindent", False)),
110
+ reindent_aligned=bool(validated.get("reindent_aligned", False)),
111
+ indent_after_first=bool(validated.get("indent_after_first", False)),
112
+ indent_columns=bool(validated.get("indent_columns", False)),
113
+ indent_tabs=bool(validated.get("indent_tabs", False)),
114
+ indent_width=int(validated.get("indent_width", 2)),
115
+ wrap_after=int(validated.get("wrap_after", 0)),
116
+ comma_first=bool(validated.get("comma_first", False)),
117
+ compact=bool(validated.get("compact", False)),
118
+ max_depth=engine.grouping.MAX_GROUPING_DEPTH,
119
+ max_tokens=engine.grouping.MAX_GROUPING_TOKENS,
120
+ )
121
+
122
+ stack = engine.FilterStack()
123
+ stack = formatter.build_filter_stack(stack, validated)
124
+ stack.postprocess.append(filters.SerializerUnicode())
125
+ return "".join(stack.run(sql_text, encoding))
126
+
127
+
128
+ def split(
129
+ sql_text: Union[str, bytes, IO[str]],
130
+ encoding: Optional[str] = None,
131
+ strip_semicolon: bool = False,
132
+ ) -> List[str]:
133
+ """Split *sql_text* into single statements.
134
+
135
+ :param sql_text: A string, bytes, or file-like object containing SQL statements.
136
+ :param encoding: The encoding of the statement (optional).
137
+ :param strip_semicolon: If True, remove trailing semicolons (default: False).
138
+ :returns: A list of strings.
139
+ """
140
+ if _can_use_rust_fast_path():
141
+ decoded = decode_input(sql_text, encoding)
142
+ return split_py(decoded, strip_semicolon)
143
+
144
+ stack = engine.FilterStack(strip_semicolon=strip_semicolon)
145
+ return [str(stmt).strip() for stmt in stack.run(sql_text, encoding)]
rsqlparse/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """CLI entry point for `python -m rsqlparse`."""
2
+
3
+ import sys
4
+
5
+ from rsqlparse.cli import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
rsqlparse/_core.pyd ADDED
Binary file
rsqlparse/_core.pyi ADDED
@@ -0,0 +1,35 @@
1
+ from typing import Any, Callable, List, Optional, Tuple
2
+
3
+ def tokenize_py(sql: str, token_types: Tuple[Any, ...]) -> List[Tuple[Any, str]]: ...
4
+ def split_py(sql: str, strip_semicolon: bool = False) -> List[str]: ...
5
+ def split_unquoted_newlines_py(text: str) -> List[str]: ...
6
+ def format_py(
7
+ sql: str,
8
+ keyword_case: Optional[str] = None,
9
+ identifier_case: Optional[str] = None,
10
+ output_format: Optional[str] = None,
11
+ strip_comments: bool = False,
12
+ use_space_around_operators: bool = False,
13
+ strip_whitespace: bool = False,
14
+ truncate_strings: Optional[int] = None,
15
+ truncate_char: str = "[...]",
16
+ reindent: bool = False,
17
+ reindent_aligned: bool = False,
18
+ indent_after_first: bool = False,
19
+ indent_columns: bool = False,
20
+ indent_tabs: bool = False,
21
+ indent_width: int = 2,
22
+ wrap_after: int = 0,
23
+ comma_first: bool = False,
24
+ compact: bool = False,
25
+ max_depth: Optional[int] = 100,
26
+ max_tokens: Optional[int] = 10000,
27
+ ) -> str: ...
28
+ def parse_py(
29
+ sql: str,
30
+ token_types: Tuple[Any, ...],
31
+ make_token: Callable[..., Any],
32
+ group_classes: Tuple[Any, ...],
33
+ max_depth: Optional[int] = 100,
34
+ max_tokens: Optional[int] = 10000,
35
+ ) -> Tuple[Any, ...]: ...
rsqlparse/cli.py ADDED
@@ -0,0 +1,245 @@
1
+ # Copyright (C) 2009-2020 the sqlparse authors and contributors
2
+ # <see AUTHORS file>
3
+ #
4
+ # This module is part of python-sqlparse and is released under
5
+ # the BSD License: https://opensource.org/licenses/BSD-3-Clause
6
+
7
+ """Module that contains the command line app.
8
+
9
+ Why does this file exist, and why not put this in __main__?
10
+ You might be tempted to import things from __main__ later, but that will
11
+ cause problems: the code will get executed twice:
12
+ - When you run `python -m sqlparse` python will execute
13
+ ``__main__.py`` as a script. That means there won't be any
14
+ ``sqlparse.__main__`` in ``sys.modules``.
15
+ - When you import __main__ it will get executed again (as a module) because
16
+ there's no ``sqlparse.__main__`` in ``sys.modules``.
17
+ Also see (1) from http://click.pocoo.org/5/setuptools/#setuptools-integration
18
+ """
19
+
20
+ import argparse
21
+ import sys
22
+ from io import TextIOWrapper
23
+
24
+ import rsqlparse as sqlparse
25
+ from rsqlparse.exceptions import SQLParseError
26
+
27
+
28
+ # TODO: Add CLI Tests
29
+ # TODO: Simplify formatter by using argparse `type` arguments
30
+ def create_parser():
31
+ _CASE_CHOICES = ['upper', 'lower', 'capitalize']
32
+
33
+ parser = argparse.ArgumentParser(
34
+ prog='sqlformat',
35
+ description='Format FILE according to OPTIONS. Use "-" as FILE '
36
+ 'to read from stdin.',
37
+ usage='%(prog)s [OPTIONS] FILE [FILE ...]',
38
+ )
39
+
40
+ parser.add_argument(
41
+ 'filename',
42
+ nargs='+',
43
+ help='file(s) to format (use "-" for stdin)')
44
+
45
+ parser.add_argument(
46
+ '-o', '--outfile',
47
+ dest='outfile',
48
+ metavar='FILE',
49
+ help='write output to FILE (defaults to stdout)')
50
+
51
+ parser.add_argument(
52
+ '--in-place',
53
+ dest='inplace',
54
+ action='store_true',
55
+ default=False,
56
+ help='format files in-place (overwrite existing files)')
57
+
58
+ parser.add_argument(
59
+ '--version',
60
+ action='version',
61
+ version=sqlparse.__version__)
62
+
63
+ group = parser.add_argument_group('Formatting Options')
64
+
65
+ group.add_argument(
66
+ '-k', '--keywords',
67
+ metavar='CHOICE',
68
+ dest='keyword_case',
69
+ choices=_CASE_CHOICES,
70
+ help='change case of keywords, CHOICE is one of {}'.format(
71
+ ', '.join(f'"{x}"' for x in _CASE_CHOICES)))
72
+
73
+ group.add_argument(
74
+ '-i', '--identifiers',
75
+ metavar='CHOICE',
76
+ dest='identifier_case',
77
+ choices=_CASE_CHOICES,
78
+ help='change case of identifiers, CHOICE is one of {}'.format(
79
+ ', '.join(f'"{x}"' for x in _CASE_CHOICES)))
80
+
81
+ group.add_argument(
82
+ '-l', '--language',
83
+ metavar='LANG',
84
+ dest='output_format',
85
+ choices=['python', 'php'],
86
+ help='output a snippet in programming language LANG, '
87
+ 'choices are "python", "php"')
88
+
89
+ group.add_argument(
90
+ '--strip-comments',
91
+ dest='strip_comments',
92
+ action='store_true',
93
+ default=False,
94
+ help='remove comments')
95
+
96
+ group.add_argument(
97
+ '-r', '--reindent',
98
+ dest='reindent',
99
+ action='store_true',
100
+ default=False,
101
+ help='reindent statements')
102
+
103
+ group.add_argument(
104
+ '--indent_width',
105
+ dest='indent_width',
106
+ default=2,
107
+ type=int,
108
+ help='indentation width (defaults to 2 spaces)')
109
+
110
+ group.add_argument(
111
+ '--indent_after_first',
112
+ dest='indent_after_first',
113
+ action='store_true',
114
+ default=False,
115
+ help='indent after first line of statement (e.g. SELECT)')
116
+
117
+ group.add_argument(
118
+ '--indent_columns',
119
+ dest='indent_columns',
120
+ action='store_true',
121
+ default=False,
122
+ help='indent all columns by indent_width instead of keyword length')
123
+
124
+ group.add_argument(
125
+ '-a', '--reindent_aligned',
126
+ action='store_true',
127
+ default=False,
128
+ help='reindent statements to aligned format')
129
+
130
+ group.add_argument(
131
+ '-s', '--use_space_around_operators',
132
+ action='store_true',
133
+ default=False,
134
+ help='place spaces around mathematical operators')
135
+
136
+ group.add_argument(
137
+ '--wrap_after',
138
+ dest='wrap_after',
139
+ default=0,
140
+ type=int,
141
+ help='Column after which lists should be wrapped')
142
+
143
+ group.add_argument(
144
+ '--comma_first',
145
+ dest='comma_first',
146
+ default=False,
147
+ type=bool,
148
+ help='Insert linebreak before comma (default False)')
149
+
150
+ group.add_argument(
151
+ '--compact',
152
+ dest='compact',
153
+ default=False,
154
+ type=bool,
155
+ help='Try to produce more compact output (default False)')
156
+
157
+ group.add_argument(
158
+ '--encoding',
159
+ dest='encoding',
160
+ default='utf-8',
161
+ help='Specify the input encoding (default utf-8)')
162
+
163
+ return parser
164
+
165
+
166
+ def _error(msg):
167
+ """Print msg and optionally exit with return code exit_."""
168
+ sys.stderr.write(f'[ERROR] {msg}\n')
169
+ return 1
170
+
171
+
172
+ def _process_file(filename, args):
173
+ """Process a single file with the given formatting options.
174
+
175
+ Returns 0 on success, 1 on error.
176
+ """
177
+ # Check for incompatible option combinations first
178
+ if filename == '-' and args.inplace:
179
+ return _error('Cannot use --in-place with stdin')
180
+
181
+ # Read input
182
+ if filename == '-': # read from stdin
183
+ wrapper = TextIOWrapper(sys.stdin.buffer, encoding=args.encoding)
184
+ try:
185
+ data = wrapper.read()
186
+ finally:
187
+ wrapper.detach()
188
+ else:
189
+ try:
190
+ with open(filename, encoding=args.encoding) as f:
191
+ data = ''.join(f.readlines())
192
+ except OSError as e:
193
+ return _error(f'Failed to read {filename}: {e}')
194
+
195
+ # Format the SQL before opening the destination. Opening it truncates
196
+ # the file, so a formatting error would otherwise leave it empty.
197
+ formatter_opts = vars(args)
198
+ try:
199
+ formatter_opts = sqlparse.formatter.validate_options(formatter_opts)
200
+ except SQLParseError as e:
201
+ return _error(f'Invalid options: {e}')
202
+
203
+ try:
204
+ s = sqlparse.format(data, **formatter_opts)
205
+ except SQLParseError as e:
206
+ return _error(f'Failed to format {filename}: {e}')
207
+
208
+ # Write output
209
+ if args.inplace:
210
+ outfile = filename
211
+ elif args.outfile:
212
+ outfile = args.outfile
213
+ else:
214
+ sys.stdout.write(s)
215
+ sys.stdout.flush()
216
+ return 0
217
+
218
+ try:
219
+ with open(outfile, 'w', encoding=args.encoding) as stream:
220
+ stream.write(s)
221
+ except OSError as e:
222
+ return _error(f'Failed to open {outfile}: {e}')
223
+ return 0
224
+
225
+
226
+ def main(args=None):
227
+ parser = create_parser()
228
+ args = parser.parse_args(args)
229
+
230
+ # Validate argument combinations
231
+ if len(args.filename) > 1:
232
+ if args.outfile:
233
+ return _error('Cannot use -o/--outfile with multiple files')
234
+ if not args.inplace:
235
+ return _error('Multiple files require --in-place flag')
236
+
237
+ # Process all files
238
+ exit_code = 0
239
+ for filename in args.filename:
240
+ result = _process_file(filename, args)
241
+ if result != 0:
242
+ exit_code = result
243
+ # Continue processing remaining files even if one fails
244
+
245
+ return exit_code
@@ -0,0 +1,16 @@
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
+ from rsqlparse.engine import grouping
9
+ from rsqlparse.engine.filter_stack import FilterStack
10
+ from rsqlparse.engine.statement_splitter import StatementSplitter
11
+
12
+ __all__ = [
13
+ 'FilterStack',
14
+ 'StatementSplitter',
15
+ 'grouping',
16
+ ]
@@ -0,0 +1,51 @@
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
+ """filter"""
9
+
10
+ from rsqlparse import lexer
11
+ from rsqlparse.engine import grouping
12
+ from rsqlparse.engine.statement_splitter import StatementSplitter
13
+ from rsqlparse.exceptions import SQLParseError
14
+ from rsqlparse.filters import StripTrailingSemicolonFilter
15
+
16
+
17
+ class FilterStack:
18
+ def __init__(self, strip_semicolon=False):
19
+ self.preprocess = []
20
+ self.stmtprocess = []
21
+ self.postprocess = []
22
+ self._grouping = False
23
+ if strip_semicolon:
24
+ self.stmtprocess.append(StripTrailingSemicolonFilter())
25
+
26
+ def enable_grouping(self):
27
+ self._grouping = True
28
+
29
+ def run(self, sql, encoding=None):
30
+ try:
31
+ stream = lexer.tokenize(sql, encoding)
32
+ # Process token stream
33
+ for filter_ in self.preprocess:
34
+ stream = filter_.process(stream)
35
+
36
+ stream = StatementSplitter().process(stream)
37
+
38
+ # Output: Stream processed Statements
39
+ for stmt in stream:
40
+ if self._grouping:
41
+ stmt = grouping.group(stmt)
42
+
43
+ for filter_ in self.stmtprocess:
44
+ filter_.process(stmt)
45
+
46
+ for filter_ in self.postprocess:
47
+ stmt = filter_.process(stmt)
48
+
49
+ yield stmt
50
+ except RecursionError as err:
51
+ raise SQLParseError('Maximum recursion depth exceeded') from err