sqlparse-turbo 0.1.0__tar.gz
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.
- sqlparse_turbo-0.1.0/LICENSE +26 -0
- sqlparse_turbo-0.1.0/PKG-INFO +349 -0
- sqlparse_turbo-0.1.0/README.md +326 -0
- sqlparse_turbo-0.1.0/pyproject.toml +39 -0
- sqlparse_turbo-0.1.0/python/sqlparse_turbo/__init__.py +435 -0
- sqlparse_turbo-0.1.0/python/sqlparse_turbo/__main__.py +20 -0
- sqlparse_turbo-0.1.0/python/sqlparse_turbo/_unicode_drift.py +62 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/.gitignore +7 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/Cargo.lock +290 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/Cargo.toml +28 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/README.md +19 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/build.rs +5 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/examples/bench_format.rs +108 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/examples/bench_lexer.rs +40 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/examples/bench_split.rs +40 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/python/sqlparse_front/__init__.py +95 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/recorded-from.json +5 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/rust-anything.json +217 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/src/filters.rs +1086 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/src/format.rs +433 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/src/grouping.rs +797 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/src/js.rs +251 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/src/lexer.rs +750 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/src/lexer_tables.rs +4515 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/src/lib.rs +407 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/src/port.rs +396 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/src/pyconv.rs +349 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/src/pynum.rs +144 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/src/pystr.rs +217 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/src/pyunicode_tables.rs +6451 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/src/split.rs +260 -0
- sqlparse_turbo-0.1.0/rust/sqlparse-front/src/tree.rs +542 -0
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
Copyright (c) 2026, the sqlparse-turbo authors
|
|
2
|
+
Copyright (c) 2016, Andi Albrecht <albrecht.andi@gmail.com> (sqlparse, which this port follows)
|
|
3
|
+
All rights reserved.
|
|
4
|
+
|
|
5
|
+
Redistribution and use in source and binary forms, with or without modification,
|
|
6
|
+
are permitted provided that the following conditions are met:
|
|
7
|
+
|
|
8
|
+
* Redistributions of source code must retain the above copyright notice,
|
|
9
|
+
this list of conditions and the following disclaimer.
|
|
10
|
+
* Redistributions in binary form must reproduce the above copyright notice,
|
|
11
|
+
this list of conditions and the following disclaimer in the documentation
|
|
12
|
+
and/or other materials provided with the distribution.
|
|
13
|
+
* Neither the name of the authors nor the names of its contributors may be
|
|
14
|
+
used to endorse or promote products derived from this software without
|
|
15
|
+
specific prior written permission.
|
|
16
|
+
|
|
17
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
|
18
|
+
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
|
19
|
+
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
20
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
|
21
|
+
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
22
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
23
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
24
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
25
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
26
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sqlparse-turbo
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Classifier: Development Status :: 4 - Beta
|
|
5
|
+
Classifier: Intended Audience :: Developers
|
|
6
|
+
Classifier: Operating System :: OS Independent
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
9
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
10
|
+
Classifier: Programming Language :: Rust
|
|
11
|
+
Classifier: Topic :: Database
|
|
12
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
13
|
+
Requires-Dist: sqlparse==0.6.1
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Summary: sqlparse's format(), split() and parse() rewritten in Rust: same output, byte for byte, many times faster
|
|
16
|
+
Keywords: sql,sqlparse,formatter,parser,rust
|
|
17
|
+
License-Expression: BSD-3-Clause
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
|
|
20
|
+
Project-URL: Issues, https://github.com/fullfud/sqlparse-turbo/issues
|
|
21
|
+
Project-URL: Repository, https://github.com/fullfud/sqlparse-turbo
|
|
22
|
+
|
|
23
|
+
# sqlparse-turbo
|
|
24
|
+
|
|
25
|
+
**[sqlparse](https://github.com/andialbrecht/sqlparse)'s `format()`, `split()` and `parse()`, rewritten in Rust:
|
|
26
|
+
same output, byte for byte, 6-100 times faster.**
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
pip install sqlparse-turbo
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
sqlparse is the pure-Python SQL splitter and formatter that Django depends on (every SQL script a migration
|
|
33
|
+
runs goes through `sqlparse.split` and `sqlparse.format`, and the test runner formats debug SQL with it), along
|
|
34
|
+
with many other tools and scripts. It is also slow: formatting two megabytes of SQL takes over ten seconds. Rust SQL libraries
|
|
35
|
+
(sqlparser-rs, sqlformat-rs, sqloxide) are fast, but they format differently, so switching to them changes
|
|
36
|
+
your output. This project ports sqlparse itself, quirks included, and proves the port gives the same answer
|
|
37
|
+
as the original on every input it has been shown.
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
import sqlparse_turbo
|
|
41
|
+
|
|
42
|
+
sqlparse_turbo.format(sql, reindent=True, keyword_case='upper') # == sqlparse.format(sql, reindent=True, ...)
|
|
43
|
+
sqlparse_turbo.split(sql) # == sqlparse.split(sql)
|
|
44
|
+
sqlparse_turbo.split_many(sqls) # split() of each, on all CPU threads
|
|
45
|
+
sqlparse_turbo.parse(sql) # == sqlparse.parse(sql): sqlparse's own objects
|
|
46
|
+
|
|
47
|
+
sqlparse_turbo.install() # from now on sqlparse.format / sqlparse.split are the Rust ones, for every caller,
|
|
48
|
+
# and sqlparse.parse and sqlparse's lexer too
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
```sh
|
|
52
|
+
sqlformat-turbo -r -k upper query.sql # sqlparse's own `sqlformat` command, formatting in Rust
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Results
|
|
56
|
+
|
|
57
|
+
The whole benchmark corpus (440 files, 2.1 MB of SQL: generated queries and scripts), sqlparse 0.6.1 against
|
|
58
|
+
`sqlparse_turbo` through the same public calls, CPython 3.11, Windows 11, best of 3, every result checked equal
|
|
59
|
+
([`bench/bench_package.py`](bench/bench_package.py)):
|
|
60
|
+
|
|
61
|
+
| Call | sqlparse | sqlparse_turbo | Speed-up |
|
|
62
|
+
| --- | ---: | ---: | ---: |
|
|
63
|
+
| `split(sql)` | 3.42 s | 0.034 s | **100x** |
|
|
64
|
+
| `format(sql, keyword_case='upper')` | 3.59 s | 0.078 s | **46x** |
|
|
65
|
+
| `format(sql, reindent=True, keyword_case='upper')` | 12.12 s | 0.404 s | **30x** |
|
|
66
|
+
| `format(sql, strip_comments=True)` | 10.58 s | 0.321 s | **33x** |
|
|
67
|
+
| `format(sql, reindent_aligned=True)` | 12.53 s | 0.395 s | **32x** |
|
|
68
|
+
| `format(sql, reindent=True, indent_columns=True, comma_first=True)` | 12.86 s | 0.408 s | **32x** |
|
|
69
|
+
|
|
70
|
+
`split_many` over the 400 query files takes 0.003 s against sqlparse's 1.07 s (12 threads), and with
|
|
71
|
+
`install()` sqlparse's `lexer.tokenize` is 20x faster.
|
|
72
|
+
|
|
73
|
+
`parse(sql)` over the 400 query files: sqlparse 3.1 s, sqlparse_turbo 0.30-0.48 s (**6-10x**); with Python's
|
|
74
|
+
cyclic garbage collector off, 2.8 s against 0.145 s (**19x**). The statements are grouped in Rust and handed
|
|
75
|
+
back as sqlparse's own `Statement`, `Identifier`, ... objects, made with `object.__new__` and their slots set
|
|
76
|
+
from the Rust tree, so a group's value joined when the group was made, `normalized` taken at creation and
|
|
77
|
+
every `parent` pointer are sqlparse's. A tree is a reference cycle (`parent` and `tokens`), so freeing one
|
|
78
|
+
waits for the garbage collector, in sqlparse as here: that collection is most of what is left.
|
|
79
|
+
|
|
80
|
+
### Against markocerkez/sqlparse-rs
|
|
81
|
+
|
|
82
|
+
[markocerkez/sqlparse-rs](https://github.com/markocerkez/sqlparse-rs) (PyPI `sqlparse-rs` 0.1.0, imported as
|
|
83
|
+
`sqlparse_rs`) ports sqlparse's lexer and `split` to Rust and leaves grouping and the filters, so `format`, in
|
|
84
|
+
Python. Both packages on the same 400 query files
|
|
85
|
+
(579 KB), same machine, best of 3, every result equal to sqlparse's:
|
|
86
|
+
|
|
87
|
+
| Call | sqlparse | markocerkez | this one |
|
|
88
|
+
| --- | ---: | ---: | ---: |
|
|
89
|
+
| `split`, each file (CPython 3.13) | 0.99 s | 0.014 s | **0.010 s** |
|
|
90
|
+
| `format(keyword_case='upper')` (3.13) | 1.05 s | 0.34 s | **0.021 s** |
|
|
91
|
+
| `format(strip_comments=True)` (3.13) | 3.2 s | 2.5 s | **0.096 s** |
|
|
92
|
+
| `format(reindent=True, keyword_case='upper')` (3.13) | 3.8 s | 3.1 s | **0.134 s** |
|
|
93
|
+
| `split_many`, all files (3.13) | 1.31 s | 0.004 s | 0.004 s |
|
|
94
|
+
| `lexer.tokenize`, each file (3.13) | 0.72 s | 0.034 s | 0.032 s |
|
|
95
|
+
| `parse`, each file (3.13) | 3.1 s | 2.36 s | **0.18 s** (0.3-0.6 s as the garbage collector runs) |
|
|
96
|
+
| `split`, each file (CPython 3.11) | 1.00 s | 0.77 s | **0.010 s** |
|
|
97
|
+
| `format(reindent=True, keyword_case='upper')` (3.11) | 3.7 s | 3.4 s | **0.13 s** |
|
|
98
|
+
|
|
99
|
+
Its Rust tables follow the Unicode version of the Python it was generated on (3.13), and on every other
|
|
100
|
+
Python it hands all non-ASCII text to sqlparse: on 3.11, 243 of the 400 files, and a script that is one of
|
|
101
|
+
them as a whole. This package keeps the Rust for all text but the few code points that changed between
|
|
102
|
+
Unicode versions (see Unicode versions below).
|
|
103
|
+
|
|
104
|
+
| What was checked | Result |
|
|
105
|
+
| --- | --- |
|
|
106
|
+
| Recorded cases (`rust-anything diff`): the original run on the corpus, sqlparse's own test files and generated edge cases, through every option | **7,842 / 7,842 identical**, errors included |
|
|
107
|
+
| sqlparse's own test suite, with `sqlparse_turbo.install()` | **537 passed**, same 2 xfail / 1 xpass as plain sqlparse |
|
|
108
|
+
| Statement trees (`tools/check_tree.py`): every node's class, value, type and parent, on the corpus, sqlparse's test files, 2,730 cuts of them, 40,000 random scripts and limit inputs | **260,837 calls, 0 differ** |
|
|
109
|
+
| Lexer (`tools/check_tokenize.py`): recorded texts, cuts of them, random texts | **32,986 texts, 0 differ** |
|
|
110
|
+
| Case filters over every Unicode code point (`tools/check_format_flat.py`) | **26.7 million texts, 0 differ** |
|
|
111
|
+
| Package against sqlparse (`tools/check_package.py`): corpus x 13 option sets, split, CLI, bad option types, lexer changes | **6,090 calls in Rust, 0 differ**; 18 out-of-range calls all answered by sqlparse |
|
|
112
|
+
| The Rust lexer under `install()`: `lexer.tokenize` and every node of `parse()` (class, token type object, value) on the corpus, sqlparse's test files and 3,000 random scripts; `split_many` against `split` | **3,460 texts, 0 differ**, all lexed in Rust; others (another Lexer, a changed one, bytes, streams) left to sqlparse |
|
|
113
|
+
| Lexer and splitter over every Unicode code point (`tools/check_codepoints.py`, `tools/check_split.py`) | **12.2 million and 10.0 million texts, 0 differ** |
|
|
114
|
+
| Patched sqlparse (`check_package.py patches`): 6 kinds of patch x format, split, parse; recursion error chain | every patched call answered by sqlparse with the patch, back in Rust once put back; `SQLParseError` from a `RecursionError` as in sqlparse |
|
|
115
|
+
| Package over every non-ASCII code point (`check_package.py unicode`), on each CPython 3.10-3.14 | the code points that behave as in 3.11 run in Rust, 0 differ; the drifted ones (see Unicode versions) go to sqlparse |
|
|
116
|
+
| Fresh random cases (`rust-anything fuzz --time 600`) | **282,550 / 282,556**; the 6 pass `None` where the front door types `str`/`bool` (a known difference of the test bindings, see below) |
|
|
117
|
+
| Python's recursion limit (`tools/check_recursion.py`): 11 deep-nesting shapes, 3 caller depths, through C calls | **fails at exactly the same size** on CPython 3.10, 3.11, 3.12, 3.13, 3.14 |
|
|
118
|
+
| Platforms, in CI ([`.github/workflows/ci.yml`](.github/workflows/ci.yml)) from the built wheel | Linux x86_64 and aarch64 (manylinux2014), Windows x64, macOS arm64 and Intel (universal2) x **CPython 3.10, 3.11, 3.12, 3.13, 3.14**: all 25 combinations pass sqlparse's suite, the recursion check and the package check (the whole check, front door included, on Linux x86_64) |
|
|
119
|
+
|
|
120
|
+
## Install
|
|
121
|
+
|
|
122
|
+
```sh
|
|
123
|
+
pip install sqlparse-turbo # pulls sqlparse==0.6.1, installs sqlparse_turbo and the sqlformat-turbo command
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Wheels are built for Linux x86_64 and aarch64, Windows x64 and macOS (arm64 and Intel), one abi3 wheel each for
|
|
127
|
+
every CPython from 3.10 on. Elsewhere pip builds from the source distribution, which needs a Rust toolchain.
|
|
128
|
+
|
|
129
|
+
From a checkout (builds with [maturin](https://www.maturin.rs/)): `pip install .`
|
|
130
|
+
|
|
131
|
+
or build wheels to copy elsewhere: `maturin build --release` (an abi3 wheel: one file for every CPython from 3.10 on).
|
|
132
|
+
`maturin build --release --zig --target x86_64-unknown-linux-gnu --compatibility manylinux2014 -i python3.11`
|
|
133
|
+
builds the Linux wheel from Windows.
|
|
134
|
+
|
|
135
|
+
## Use
|
|
136
|
+
|
|
137
|
+
`sqlparse_turbo.format(sql, encoding=None, **options)` and `sqlparse_turbo.split(sql, encoding=None,
|
|
138
|
+
strip_semicolon=False)` take exactly what sqlparse's take and return exactly what they return, errors
|
|
139
|
+
included: an invalid option raises `sqlparse.exceptions.SQLParseError` with sqlparse's message, and a
|
|
140
|
+
statement nested past Python's recursion limit raises sqlparse's `SQLParseError('Maximum recursion depth
|
|
141
|
+
exceeded')` at the same nesting depth.
|
|
142
|
+
|
|
143
|
+
`sqlparse_turbo.split_many(sqls, strip_semicolon=False)` is `[sqlparse.split(s) for s in sqls]`, with the texts
|
|
144
|
+
split in Rust on all CPU threads at once and Python's lock released (texts the Rust does not take go to
|
|
145
|
+
sqlparse one by one). `split` releases the lock too, so other Python threads run meanwhile.
|
|
146
|
+
|
|
147
|
+
`sqlparse_turbo.install()` replaces `sqlparse.format` and `sqlparse.split` on the module, so every caller that
|
|
148
|
+
writes `sqlparse.format(...)` (Django's `prepare_sql_script` and test runner, the `sqlformat` CLI) gets the Rust
|
|
149
|
+
without changing a line. It also gives sqlparse's default lexer the Rust tokenizer (`Lexer.get_tokens`), so
|
|
150
|
+
`sqlparse.parse()` and everything else that tokenizes gets faster too: the same (token type, value) pairs, with
|
|
151
|
+
sqlparse's own token type objects, and only for the default lexer as sqlparse sets it up and a `str` the Rust
|
|
152
|
+
takes. A name bound before with `from sqlparse import format` keeps the original. `uninstall()` puts sqlparse's
|
|
153
|
+
functions back. `install()` refuses (returns False) if the installed sqlparse is not 0.6.1.
|
|
154
|
+
|
|
155
|
+
`sqlformat-turbo` (or `python -m sqlparse_turbo`) is sqlparse's `sqlformat`, same arguments, output and exit codes.
|
|
156
|
+
|
|
157
|
+
### When the Rust runs, and when sqlparse does
|
|
158
|
+
|
|
159
|
+
A call runs in Rust only when it is inside what was proven. Everything else goes to sqlparse itself,
|
|
160
|
+
unchanged, so the answer is always sqlparse's:
|
|
161
|
+
|
|
162
|
+
| Runs in Rust | Goes to sqlparse |
|
|
163
|
+
| --- | --- |
|
|
164
|
+
| sqlparse 0.6.1 installed | any other sqlparse version |
|
|
165
|
+
| `sql` is a `str` (any `encoding`: sqlparse only uses it for bytes) | bytes, a stream, a `str` subclass, a `str` with lone surrogates |
|
|
166
|
+
| sqlparse's default lexer as sqlparse sets it up | after `Lexer.add_keywords`, `set_SQL_REGEX`, `clear` (Rust again after `default_initialization()`) |
|
|
167
|
+
| options of exactly the type the port takes: `True`/`False`, `int`, `str`, `None` where allowed | `reindent=1`, `reindent=None`, `indent_width=4.0`, a `str` subclass, an `int` past 64 bits |
|
|
168
|
+
| `indent_width` up to 4096 | a larger `indent_width` (see Limits) |
|
|
169
|
+
| text whose characters this Python's Unicode tables treat as CPython 3.11's do (all ASCII text, nearly all other) | text holding a code point that changed since Unicode 14 on this Python (see below) |
|
|
170
|
+
| keywords sqlparse never reads (`filename`, `outfile`, ... as the CLI passes them) are dropped, as sqlparse ignores them | |
|
|
171
|
+
| sqlparse's code as installed (Rust again once a change is put back) | a replaced, wrapped, added or deleted function, method, class or constant in sqlparse's modules (grouping, filters, `sql`, `tokens`, keywords, lexer, ...) |
|
|
172
|
+
|
|
173
|
+
The rules are in [`python/sqlparse_turbo/__init__.py`](python/sqlparse_turbo/__init__.py).
|
|
174
|
+
|
|
175
|
+
**Patched sqlparse.** A program that monkeypatches sqlparse (`grouping.group_identifier = ...`, a new method
|
|
176
|
+
on `Identifier`, `MAX_GROUPING_TOKENS = 5`) gets its patch: the package remembers every name in sqlparse's
|
|
177
|
+
modules and classes at import and sends calls to sqlparse while one of them differs. On CPython 3.12+ Python
|
|
178
|
+
tells the package when one of those dicts changes (a dict watcher), so the comparison runs once after a change
|
|
179
|
+
and a call pays well under a microsecond for it; on 3.10 and 3.11 it runs on every call, about 7 µs (a
|
|
180
|
+
`format("select 1")` takes ~10 µs there against ~3 µs on 3.13).
|
|
181
|
+
|
|
182
|
+
**Unicode versions.** The Rust's character tables (`\w`, `\d`, case mapping, `isprintable`, line breaks, final
|
|
183
|
+
sigma) are taken from CPython 3.11, which has Unicode 14. Other CPythons ship other Unicode versions: 3.10 has
|
|
184
|
+
13.0, 3.12 has 15.0, 3.13 has 15.1, 3.14 has 16.0, and on each some code points behave differently (newly
|
|
185
|
+
assigned CJK letters become `\w` and case-insensitive keyword matching changes around them, for example). sqlparse
|
|
186
|
+
follows the Python it runs on, so a text holding such a code point goes to sqlparse.
|
|
187
|
+
[`tools/unicode_drift.py`](tools/unicode_drift.py) compares every code point's behaviour on each CPython with
|
|
188
|
+
3.11's and writes the list ([`_unicode_drift.py`](python/sqlparse_turbo/_unicode_drift.py): 839 code points for
|
|
189
|
+
Unicode 13, 4,489 / 5,116 / 10,304 for 15.0 / 15.1 / 16.0). On a Unicode version not in the list, only ASCII text
|
|
190
|
+
runs in Rust. The list goes to the Rust once, as one bit per code point, and a text is checked in one pass.
|
|
191
|
+
|
|
192
|
+
`sqlparse_turbo.parse(sql, encoding=None)` returns what `sqlparse.parse` returns: a tuple of sqlparse's own
|
|
193
|
+
`Statement` objects, node for node, for callers to walk and change; `install()` puts it in place of
|
|
194
|
+
`sqlparse.parse` (`parsestream`, a generator, stays sqlparse's). It runs in Rust under the same conditions as
|
|
195
|
+
`format()`, and raises sqlparse's `SQLParseError` at the same nesting depth.
|
|
196
|
+
|
|
197
|
+
## How it is proven
|
|
198
|
+
|
|
199
|
+
The port is checked with [rust-anything](https://github.com/erkamyaman/rust-anything), a tool that records a
|
|
200
|
+
Python library's behaviour and replays it against a Rust port:
|
|
201
|
+
|
|
202
|
+
1. `upstream/` is sqlparse itself, a git submodule pinned to release **0.6.1**. Nothing in it is changed.
|
|
203
|
+
2. [`front/sqlparse_front.py`](front/sqlparse_front.py) is the front door: `tokenize`, `split`, `format`
|
|
204
|
+
with every option, and `parse_tree` (`parse()`'s tree as plain lists, so the tree is compared node by node).
|
|
205
|
+
3. `rust-anything record` runs the original on generated edge cases and real SQL
|
|
206
|
+
([`bench/make_inputs.py`](bench/make_inputs.py): the benchmark corpus and sqlparse's own test files, through
|
|
207
|
+
the option sets people use) and saves what every call returns or raises.
|
|
208
|
+
4. `rust-anything diff` replays all of it against the Rust (`rust/sqlparse-front/`); `fuzz` generates fresh
|
|
209
|
+
inputs and compares the two live; `gate` runs fmt, clippy, tests, no-`unsafe`, no-panic and the replay.
|
|
210
|
+
5. The scripts in [`tools/`](tools) go further than the recording: every Unicode code point through the
|
|
211
|
+
lexer and case filters, hundreds of thousands of trees, the recursion threshold, and the package's public
|
|
212
|
+
calls against sqlparse's.
|
|
213
|
+
|
|
214
|
+
### How the lexer matches Python's `re`
|
|
215
|
+
|
|
216
|
+
Python 3.11 and Rust disagree on `\w`, `\s`, `\d`, `\b` and case-insensitive letters outside ASCII (Unicode 14
|
|
217
|
+
against a newer table, combining marks, numerics like `½`, `ſ` and the Kelvin sign).
|
|
218
|
+
[`tools/gen_lexer.py`](tools/gen_lexer.py) writes `src/lexer_tables.rs` from sqlparse itself: every character
|
|
219
|
+
class in `SQL_REGEX` becomes the exact set of code points Python's `re` matches, asked code point by code
|
|
220
|
+
point. Patterns with lookahead run on fancy-regex, so backtracking behaves as in `re` (`123abc` lexes as `12`
|
|
221
|
+
+ `3abc` in both); one-character lookbehinds are checked on the character before the match. Each rule gets the
|
|
222
|
+
set of characters a match can start with, so a position only tries the rules that can match there, and each
|
|
223
|
+
rule with lookaround gets a lookaround-free *prefilter* that every match also matches, run first on the
|
|
224
|
+
regex crate's DFA: where it finds nothing, the slow backtracking engine is skipped.
|
|
225
|
+
|
|
226
|
+
### How the tree matches sqlparse's
|
|
227
|
+
|
|
228
|
+
[`src/tree.rs`](rust/sqlparse-front/src/tree.rs) is `sql.py` on an arena,
|
|
229
|
+
[`src/grouping.rs`](rust/sqlparse-front/src/grouping.rs) is `grouping.py` function by function, and
|
|
230
|
+
[`src/filters.rs`](rust/sqlparse-front/src/filters.rs) the filters that work on the tree. What sqlparse does by
|
|
231
|
+
accident is kept, because output depends on it:
|
|
232
|
+
|
|
233
|
+
- a group's `value` is joined when the group is made and never refreshed: the reindent filter measures
|
|
234
|
+
identifiers by it, and the Python/PHP output filters print it, after strip_whitespace has changed the
|
|
235
|
+
leaves (`str()` is recomputed from the leaves, as in Python);
|
|
236
|
+
- `normalized`, `is_keyword` and `is_whitespace` are taken at creation (`group_operator` later retypes `*`);
|
|
237
|
+
- `_group` walks a copy of the list taken at the start, so a token already moved into a group is still looked
|
|
238
|
+
at, with an index that is off; `tidx_offset` and the stale `prev_` are reproduced;
|
|
239
|
+
- `ttype in T.X` (subtypes) against `ttype in (T.X, T.Y)` (equality) and `isinstance(x, TokenList)` (any group)
|
|
240
|
+
are told apart everywhere;
|
|
241
|
+
- tokens put in with `tokens.insert` have no parent, which `_current_line_len` and `within()` see;
|
|
242
|
+
- with an output format, the statement's tokens become a generator the serializer uses up, so the reindent
|
|
243
|
+
filter separates the next statement as if the last one were `''`;
|
|
244
|
+
- the limits raise what sqlparse raises: grouping depth 100, 10,000 tokens, `right_margin` is
|
|
245
|
+
`NotImplementedError`, and Python's own recursion limit, which ~980 nested BEGIN blocks or BETWEEN chains
|
|
246
|
+
reach. The port counts the frames sqlparse would use from the caller's real stack depth, asks Python for
|
|
247
|
+
the exact headroom when close to the limit, and knows that CPython 3.12+ no longer counts C calls (such as
|
|
248
|
+
`''.join`) against it, so it fails from exactly the same size as sqlparse on every version.
|
|
249
|
+
|
|
250
|
+
## Speed
|
|
251
|
+
|
|
252
|
+
The Rust alone, no Python (`cargo run --release --example bench_format`, `bench_lexer`, `bench_split`), same
|
|
253
|
+
corpus, best of 3, before and after the last optimisation pass:
|
|
254
|
+
|
|
255
|
+
| Step | first port | regex lexer | now |
|
|
256
|
+
| --- | ---: | ---: | ---: |
|
|
257
|
+
| lex (`tokenize`, 799k tokens) | 0.19 s | 0.087 s | **0.026 s** |
|
|
258
|
+
| `split` | 0.21 s | 0.10 s | **0.032 s** |
|
|
259
|
+
| `parse` (lex, split, group) | 0.50 s | 0.36 s | **0.30 s** |
|
|
260
|
+
| `format(reindent=True, keyword_case='upper')` | 0.62 s | 0.48 s | **0.41 s** |
|
|
261
|
+
| `format(strip_comments=True)` | 0.49 s | 0.37 s | **0.28 s** |
|
|
262
|
+
| `format(reindent_aligned=True)` | 0.55 s | 0.41 s | **0.34 s** |
|
|
263
|
+
|
|
264
|
+
The last step was the lexer. 88 % of tokens (spaces, words, punctuation, numbers, strings, comparison
|
|
265
|
+
operators) are now recognised by hand-written matchers that decide sqlparse's rules in sqlparse's order:
|
|
266
|
+
`fast_token` in [`src/lexer.rs`](rust/sqlparse-front/src/lexer.rs). Tests pin which rules each character can
|
|
267
|
+
start, and every other case still runs the regexes: a non-ASCII character where `\w` or `\d` would matter,
|
|
268
|
+
`$`/`#` in a word, an unclosed string, a word that can open a multi-word keyword (`GROUP BY`, `LEFT JOIN`; then
|
|
269
|
+
only that keyword's own rules run). The splitter stopped allocating for keywords and slices statements straight
|
|
270
|
+
out of the text.
|
|
271
|
+
|
|
272
|
+
The package adds little on top (the string crosses into Rust and back once per call, plus a look at the
|
|
273
|
+
Python stack for the recursion limit).
|
|
274
|
+
|
|
275
|
+
Where the Rust spends its time now on `format(reindent=True)`, whole corpus: grouping 40 % (spread over 19
|
|
276
|
+
passes, the largest, `group_matching`, 8 %), lexing 20 %, the reindent filter 18 %, building the tree and
|
|
277
|
+
copying tokens 8 %. No single hot spot is left; going further would mean merging grouping passes, which
|
|
278
|
+
sqlparse runs one after another over the whole tree and whose order the output depends on.
|
|
279
|
+
|
|
280
|
+
What made it fast besides being Rust: tokens are spans into one string, the tree is an arena of indices,
|
|
281
|
+
grouping passes walk the tree instead of rebuilding lists, keyword lookups use a sorted table without
|
|
282
|
+
allocating, and the lexer skips most regex work (first-character table, DFA prefilters for lookaround rules:
|
|
283
|
+
the last pass made the lexer 2.2x faster with them).
|
|
284
|
+
sqlparse spends 58 % of `format()` in grouping, 27 % lexing and splitting and 9 % in the reindent filter
|
|
285
|
+
([`docs/profile-format.md`](docs/profile-format.md)); its quadratic spots (`_current_line_len` re-joining the
|
|
286
|
+
whole statement for every line) are walked backwards to the last line break in the port.
|
|
287
|
+
|
|
288
|
+
## Limits and known differences
|
|
289
|
+
|
|
290
|
+
- **Out of memory.** sqlparse raises `MemoryError`; Rust cannot catch a failed allocation and stops the
|
|
291
|
+
process. The indent string, the one thing that grows with an option rather than with the input, is
|
|
292
|
+
allocated as Python does it (`OverflowError` past `sys.maxsize`, `MemoryError` when it cannot be had), but a
|
|
293
|
+
later copy of a gigabyte-sized result can still fail. Only a huge `indent_width` makes a small statement
|
|
294
|
+
that big, so the package gives `indent_width` above 4096 to sqlparse.
|
|
295
|
+
- **A call the package hands to sqlparse** has the package's frame on the stack as well, so sqlparse's own
|
|
296
|
+
recursion limit comes one nesting level sooner than when called directly.
|
|
297
|
+
- **The `RecursionError` behind the recursion `SQLParseError`** says `maximum recursion depth exceeded`. On
|
|
298
|
+
CPython 3.10 sqlparse's says where Python hit the limit as well (`... in comparison`, `... in
|
|
299
|
+
__instancecheck__`), which depends on the C call sqlparse was in; the `SQLParseError` itself is the same.
|
|
300
|
+
- **The front-door bindings** (`rust/sqlparse-front`, used for the recording) take typed arguments: `None`
|
|
301
|
+
for a bool option is a `TypeError` there, where sqlparse treats it as False. The package never sends such
|
|
302
|
+
calls to the Rust.
|
|
303
|
+
- **Exception class** needs rust-anything with dotted exception kinds
|
|
304
|
+
([erkamyaman/rust-anything#207](https://github.com/erkamyaman/rust-anything/pull/207), not merged yet) to
|
|
305
|
+
regenerate the bindings; the bindings in this repository already raise sqlparse's own `SQLParseError`.
|
|
306
|
+
- **Not tested:** Windows on ARM, musl (Alpine), PyPy, free-threaded CPython; no wheels are built for them.
|
|
307
|
+
|
|
308
|
+
## Layout
|
|
309
|
+
|
|
310
|
+
| Path | What |
|
|
311
|
+
| --- | --- |
|
|
312
|
+
| `python/sqlparse_turbo/` | the package: `format`, `split`, `install`, the CLI |
|
|
313
|
+
| `rust/sqlparse-front/src/` | the port: `lexer.rs`, `split.rs`, `tree.rs`, `grouping.rs`, `filters.rs`, `format.rs`, `port.rs` (about 3,800 hand-written lines); `lexer_tables.rs`, `pyunicode_tables.rs` are generated from Python by `tools/gen_lexer.py` and `tools/gen_unicode.py`; `lib.rs` and the conversions are generated by rust-anything |
|
|
314
|
+
| `front/` | the front door rust-anything records and replays |
|
|
315
|
+
| `upstream/` | sqlparse 0.6.1 (git submodule) |
|
|
316
|
+
| `bench/` | corpus generator (`gen_corpus.py`, same seed = same bytes), Python workload, recording inputs, `bench_package.py` |
|
|
317
|
+
| `tools/` | the checks listed above, generators, `run_upstream_package.py` |
|
|
318
|
+
|
|
319
|
+
## Development
|
|
320
|
+
|
|
321
|
+
```sh
|
|
322
|
+
git submodule update --init
|
|
323
|
+
python -m venv .venv && .venv/Scripts/python -m pip install -e ./upstream pytest maturin
|
|
324
|
+
.venv/Scripts/python -X utf8 bench/gen_corpus.py # the corpus (not committed)
|
|
325
|
+
.venv/Scripts/python -X utf8 bench/make_inputs.py # inputs for the recording
|
|
326
|
+
|
|
327
|
+
# the port, with .venv/Scripts first on PATH so rust-anything's Python sees the pinned sqlparse:
|
|
328
|
+
rust-anything record rust/sqlparse-front --inputs rust/sqlparse-front/inputs.jsonl
|
|
329
|
+
rust-anything build rust/sqlparse-front
|
|
330
|
+
rust-anything diff rust/sqlparse-front
|
|
331
|
+
rust-anything gate rust/sqlparse-front
|
|
332
|
+
cargo run --release --manifest-path rust/sqlparse-front/Cargo.toml --example bench_format # Rust alone
|
|
333
|
+
|
|
334
|
+
# the package:
|
|
335
|
+
VIRTUAL_ENV=.venv maturin develop --release
|
|
336
|
+
.venv/Scripts/python -X utf8 tools/run_upstream_package.py
|
|
337
|
+
.venv/Scripts/python -X utf8 tools/check_package.py
|
|
338
|
+
.venv/Scripts/python -X utf8 tools/check_recursion.py package
|
|
339
|
+
.venv/Scripts/python -X utf8 bench/bench_package.py
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
`rust-anything gate` passes everything except `size`: it compares the Rust's line count with the 59-line
|
|
343
|
+
front door, and most of the Rust is the generated Unicode and lexer tables.
|
|
344
|
+
|
|
345
|
+
## License
|
|
346
|
+
|
|
347
|
+
BSD-3-Clause, like sqlparse ([`LICENSE`](LICENSE)). The port follows sqlparse's code closely, so sqlparse's
|
|
348
|
+
copyright notice is kept next to ours.
|
|
349
|
+
|