sqlparse-turbo 0.1.0__tar.gz → 0.1.1__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.
Files changed (32) hide show
  1. sqlparse_turbo-0.1.0/README.md → sqlparse_turbo-0.1.1/PKG-INFO +102 -6
  2. sqlparse_turbo-0.1.0/PKG-INFO → sqlparse_turbo-0.1.1/README.md +73 -29
  3. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/pyproject.toml +10 -3
  4. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/python/sqlparse_turbo/__init__.py +78 -12
  5. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/src/lib.rs +9 -4
  6. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/src/port.rs +28 -4
  7. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/LICENSE +0 -0
  8. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/python/sqlparse_turbo/__main__.py +0 -0
  9. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/python/sqlparse_turbo/_unicode_drift.py +0 -0
  10. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/.gitignore +0 -0
  11. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/Cargo.lock +0 -0
  12. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/Cargo.toml +0 -0
  13. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/README.md +0 -0
  14. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/build.rs +0 -0
  15. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/examples/bench_format.rs +0 -0
  16. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/examples/bench_lexer.rs +0 -0
  17. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/examples/bench_split.rs +0 -0
  18. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/python/sqlparse_front/__init__.py +0 -0
  19. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/recorded-from.json +0 -0
  20. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/rust-anything.json +0 -0
  21. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/src/filters.rs +0 -0
  22. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/src/format.rs +0 -0
  23. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/src/grouping.rs +0 -0
  24. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/src/js.rs +0 -0
  25. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/src/lexer.rs +0 -0
  26. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/src/lexer_tables.rs +0 -0
  27. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/src/pyconv.rs +0 -0
  28. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/src/pynum.rs +0 -0
  29. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/src/pystr.rs +0 -0
  30. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/src/pyunicode_tables.rs +0 -0
  31. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/src/split.rs +0 -0
  32. {sqlparse_turbo-0.1.0 → sqlparse_turbo-0.1.1}/rust/sqlparse-front/src/tree.rs +0 -0
@@ -1,12 +1,59 @@
1
- # sqlparse-turbo
2
-
3
- **[sqlparse](https://github.com/andialbrecht/sqlparse)'s `format()`, `split()` and `parse()`, rewritten in Rust:
4
- same output, byte for byte, 6-100 times faster.**
1
+ Metadata-Version: 2.4
2
+ Name: sqlparse-turbo
3
+ Version: 0.1.1
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 :: 3.10
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Classifier: Framework :: Django
15
+ Classifier: Programming Language :: Python :: Implementation :: CPython
16
+ Classifier: Programming Language :: Rust
17
+ Classifier: Topic :: Database
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Requires-Dist: sqlparse>=0.4
20
+ License-File: LICENSE
21
+ Summary: sqlparse 0.6.1's format(), split() and parse() rewritten in Rust: same output, byte for byte, many times faster
22
+ Keywords: sql,sqlparse,formatter,parser,rust
23
+ License-Expression: BSD-3-Clause
24
+ Requires-Python: >=3.10
25
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
26
+ Project-URL: Issues, https://github.com/fullfud/sqlparse-turbo/issues
27
+ Project-URL: Repository, https://github.com/fullfud/sqlparse-turbo
28
+
29
+ <h1 align="center">sqlparse-turbo</h1>
30
+
31
+ <p align="center">
32
+ <a href="https://pypi.org/project/sqlparse-turbo/"><img src="https://img.shields.io/pypi/v/sqlparse-turbo?color=FF8A3D&label=PyPI" alt="PyPI version"></a>
33
+ <a href="https://pypi.org/project/sqlparse-turbo/"><img src="https://img.shields.io/pypi/pyversions/sqlparse-turbo" alt="Python versions"></a>
34
+ <a href="https://github.com/fullfud/sqlparse-turbo/actions/workflows/ci.yml"><img src="https://github.com/fullfud/sqlparse-turbo/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
35
+ <img src="https://img.shields.io/badge/Linux%20·%20macOS%20·%20Windows-wheels-2563EB" alt="Wheels for Linux, macOS and Windows">
36
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-BSD--3--Clause-555" alt="BSD-3-Clause license"></a>
37
+ </p>
38
+
39
+ <p align="center"><b><a href="https://github.com/andialbrecht/sqlparse">sqlparse</a>'s <code>format()</code>,
40
+ <code>split()</code> and <code>parse()</code>, rewritten in Rust:<br>same output, byte for byte, 17-113 times
41
+ faster.</b></p>
42
+
43
+ <p align="center">
44
+ <img src="https://raw.githubusercontent.com/fullfud/sqlparse-turbo/main/docs/assets/race.gif" alt="sqlparse.format(reindent=True, keyword_case='upper') over 400 SQL queries, each file at its measured time: sqlparse takes 3.68 s, sqlparse-turbo 0.12 s, and both give the same output (same sha256)." width="820">
45
+ </p>
5
46
 
6
47
  ```sh
7
- pip install sqlparse-turbo
48
+ pip install sqlparse-turbo "sqlparse==0.6.1"
8
49
  ```
9
50
 
51
+ > [!IMPORTANT]
52
+ > **The speed-up needs sqlparse 0.6.1**, sqlparse's current release. The Rust is a port of that version and runs
53
+ > only with it. With any other sqlparse the package still installs and every answer is still right, but every
54
+ > call simply goes to sqlparse at sqlparse's own speed: `install()` returns False, `sqlparse_turbo.ACTIVE` is
55
+ > False, and importing the package warns about it.
56
+
10
57
  sqlparse is the pure-Python SQL splitter and formatter that Django depends on (every SQL script a migration
11
58
  runs goes through `sqlparse.split` and `sqlparse.format`, and the test runner formats debug SQL with it), along
12
59
  with many other tools and scripts. It is also slow: formatting two megabytes of SQL takes over ten seconds. Rust SQL libraries
@@ -30,8 +77,35 @@ sqlparse_turbo.install() # from now on sqlparse.format / sqlparse.split are t
30
77
  sqlformat-turbo -r -k upper query.sql # sqlparse's own `sqlformat` command, formatting in Rust
31
78
  ```
32
79
 
80
+ ## Django
81
+
82
+ Django and its tools call sqlparse themselves. One line at the top of `settings.py` gives all of them the Rust,
83
+ with nothing else changed:
84
+
85
+ ```python
86
+ import sqlparse_turbo
87
+ sqlparse_turbo.install()
88
+ ```
89
+
90
+ - **[django-debug-toolbar](https://github.com/django-commons/django-debug-toolbar)** formats every query of a
91
+ page for its SQL panel with its own sqlparse filter stack. With `install()` the statements come grouped from
92
+ the Rust and only the toolbar's own filters run in Python: the panel formats the 400 corpus queries
93
+ **4.2x faster** (4.92 s → 1.17 s), the HTML identical, and a page making 200 ORM queries loads **2x faster**
94
+ through the toolbar (0.60 s → 0.30 s, the rest being the queries themselves and the templates).
95
+ Measured with [`bench/django_toolbar.py`](bench/django_toolbar.py), Django 6.1, django-debug-toolbar 8.0,
96
+ Python 3.13.
97
+ - **Migrations** with `RunSQL` scripts and `sqlmigrate` go through `sqlparse.split` and `sqlparse.format`.
98
+ - **Tests**: the runner formats debug SQL with `sqlparse.format`.
99
+
33
100
  ## Results
34
101
 
102
+ <p align="center">
103
+ <img src="https://raw.githubusercontent.com/fullfud/sqlparse-turbo/main/docs/assets/speed.svg" alt="Seconds for 400 SQL queries, one call per file, Python 3.13: split 0.93 s against 0.008 s (113x), format with keyword_case 0.99 s against 0.019 s (53x), format with reindent 3.68 s against 0.121 s (30x), parse 2.96 s against 0.175 s (17x)." width="760">
104
+ </p>
105
+
106
+ The chart and the animation above come from [`bench/race_times.py`](bench/race_times.py) (best of 3 per file,
107
+ every result checked equal) and [`tools/make_visuals.py`](tools/make_visuals.py).
108
+
35
109
  The whole benchmark corpus (440 files, 2.1 MB of SQL: generated queries and scripts), sqlparse 0.6.1 against
36
110
  `sqlparse_turbo` through the same public calls, CPython 3.11, Windows 11, best of 3, every result checked equal
37
111
  ([`bench/bench_package.py`](bench/bench_package.py)):
@@ -90,6 +164,8 @@ Unicode versions (see Unicode versions below).
90
164
  | 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 |
91
165
  | 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** |
92
166
  | 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 |
167
+ | Callers' own filter stacks through `FilterStack.run` (`check_package.py stacks`; `check_recursion.py package`): grouping only, the indent filters, a filter of the caller's own, serializers | same trees and output as sqlparse's run, the recursion error from exactly the same size |
168
+ | Other sqlparse versions (`check_other_sqlparse.py`, in CI with 0.4.4, 0.5.3, 0.6.0) | every call answered by that sqlparse, nothing reaches the Rust |
93
169
  | 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 |
94
170
  | 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) |
95
171
  | 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 |
@@ -98,9 +174,20 @@ Unicode versions (see Unicode versions below).
98
174
  ## Install
99
175
 
100
176
  ```sh
101
- pip install sqlparse-turbo # pulls sqlparse==0.6.1, installs sqlparse_turbo and the sqlformat-turbo command
177
+ pip install sqlparse-turbo "sqlparse==0.6.1" # sqlparse_turbo, the sqlformat-turbo command, and sqlparse 0.6.1
102
178
  ```
103
179
 
180
+ Only sqlparse 0.6.1 gets the Rust. The package does not require that version (requiring it would stop a project
181
+ pinned to another sqlparse from installing it at all), so pip keeps whatever sqlparse a project already has. On
182
+ another version everything works as plain sqlparse, no faster, and the import warns:
183
+
184
+ ```
185
+ RuntimeWarning: sqlparse_turbo runs in Rust only with sqlparse 0.6.1; sqlparse 0.5.3 is installed, so every call
186
+ goes to sqlparse at its own speed (pip install "sqlparse==0.6.1")
187
+ ```
188
+
189
+ `sqlparse_turbo.ACTIVE` tells which it is.
190
+
104
191
  Wheels are built for Linux x86_64 and aarch64, Windows x64 and macOS (arm64 and Intel), one abi3 wheel each for
105
192
  every CPython from 3.10 on. Elsewhere pip builds from the source distribution, which needs a Rust toolchain.
106
193
 
@@ -130,6 +217,11 @@ sqlparse's own token type objects, and only for the default lexer as sqlparse se
130
217
  takes. A name bound before with `from sqlparse import format` keeps the original. `uninstall()` puts sqlparse's
131
218
  functions back. `install()` refuses (returns False) if the installed sqlparse is not 0.6.1.
132
219
 
220
+ `install()` also replaces `FilterStack.run`, which callers use to run their own sqlparse filters
221
+ (django-debug-toolbar's SQL panel): a stack with grouping on and no token-stream filters gets its statements
222
+ grouped in Rust, as `parse()` makes them, and runs its own statement filters and serializers on them in Python.
223
+ Any other stack runs as sqlparse's.
224
+
133
225
  `sqlformat-turbo` (or `python -m sqlparse_turbo`) is sqlparse's `sqlformat`, same arguments, output and exit codes.
134
226
 
135
227
  ### When the Rust runs, and when sqlparse does
@@ -272,6 +364,9 @@ whole statement for every line) are walked backwards to the last line break in t
272
364
  that big, so the package gives `indent_width` above 4096 to sqlparse.
273
365
  - **A call the package hands to sqlparse** has the package's frame on the stack as well, so sqlparse's own
274
366
  recursion limit comes one nesting level sooner than when called directly.
367
+ - **`FilterStack.run` with `install()`** decides between the Rust and sqlparse's own run when it is called;
368
+ sqlparse's reads the stack's filters when the first statement is asked for, so a filter added to the stack
369
+ after `run()` was called but before iterating is not seen.
275
370
  - **The `RecursionError` behind the recursion `SQLParseError`** says `maximum recursion depth exceeded`. On
276
371
  CPython 3.10 sqlparse's says where Python hit the limit as well (`... in comparison`, `... in
277
372
  __instancecheck__`), which depends on the C call sqlparse was in; the `SQLParseError` itself is the same.
@@ -324,3 +419,4 @@ front door, and most of the Rust is the generated Unicode and lexer tables.
324
419
 
325
420
  BSD-3-Clause, like sqlparse ([`LICENSE`](LICENSE)). The port follows sqlparse's code closely, so sqlparse's
326
421
  copyright notice is kept next to ours.
422
+
@@ -1,34 +1,31 @@
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.**
1
+ <h1 align="center">sqlparse-turbo</h1>
2
+
3
+ <p align="center">
4
+ <a href="https://pypi.org/project/sqlparse-turbo/"><img src="https://img.shields.io/pypi/v/sqlparse-turbo?color=FF8A3D&label=PyPI" alt="PyPI version"></a>
5
+ <a href="https://pypi.org/project/sqlparse-turbo/"><img src="https://img.shields.io/pypi/pyversions/sqlparse-turbo" alt="Python versions"></a>
6
+ <a href="https://github.com/fullfud/sqlparse-turbo/actions/workflows/ci.yml"><img src="https://github.com/fullfud/sqlparse-turbo/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
7
+ <img src="https://img.shields.io/badge/Linux%20·%20macOS%20·%20Windows-wheels-2563EB" alt="Wheels for Linux, macOS and Windows">
8
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-BSD--3--Clause-555" alt="BSD-3-Clause license"></a>
9
+ </p>
10
+
11
+ <p align="center"><b><a href="https://github.com/andialbrecht/sqlparse">sqlparse</a>'s <code>format()</code>,
12
+ <code>split()</code> and <code>parse()</code>, rewritten in Rust:<br>same output, byte for byte, 17-113 times
13
+ faster.</b></p>
14
+
15
+ <p align="center">
16
+ <img src="https://raw.githubusercontent.com/fullfud/sqlparse-turbo/main/docs/assets/race.gif" alt="sqlparse.format(reindent=True, keyword_case='upper') over 400 SQL queries, each file at its measured time: sqlparse takes 3.68 s, sqlparse-turbo 0.12 s, and both give the same output (same sha256)." width="820">
17
+ </p>
27
18
 
28
19
  ```sh
29
- pip install sqlparse-turbo
20
+ pip install sqlparse-turbo "sqlparse==0.6.1"
30
21
  ```
31
22
 
23
+ > [!IMPORTANT]
24
+ > **The speed-up needs sqlparse 0.6.1**, sqlparse's current release. The Rust is a port of that version and runs
25
+ > only with it. With any other sqlparse the package still installs and every answer is still right, but every
26
+ > call simply goes to sqlparse at sqlparse's own speed: `install()` returns False, `sqlparse_turbo.ACTIVE` is
27
+ > False, and importing the package warns about it.
28
+
32
29
  sqlparse is the pure-Python SQL splitter and formatter that Django depends on (every SQL script a migration
33
30
  runs goes through `sqlparse.split` and `sqlparse.format`, and the test runner formats debug SQL with it), along
34
31
  with many other tools and scripts. It is also slow: formatting two megabytes of SQL takes over ten seconds. Rust SQL libraries
@@ -52,8 +49,35 @@ sqlparse_turbo.install() # from now on sqlparse.format / sqlparse.split are t
52
49
  sqlformat-turbo -r -k upper query.sql # sqlparse's own `sqlformat` command, formatting in Rust
53
50
  ```
54
51
 
52
+ ## Django
53
+
54
+ Django and its tools call sqlparse themselves. One line at the top of `settings.py` gives all of them the Rust,
55
+ with nothing else changed:
56
+
57
+ ```python
58
+ import sqlparse_turbo
59
+ sqlparse_turbo.install()
60
+ ```
61
+
62
+ - **[django-debug-toolbar](https://github.com/django-commons/django-debug-toolbar)** formats every query of a
63
+ page for its SQL panel with its own sqlparse filter stack. With `install()` the statements come grouped from
64
+ the Rust and only the toolbar's own filters run in Python: the panel formats the 400 corpus queries
65
+ **4.2x faster** (4.92 s → 1.17 s), the HTML identical, and a page making 200 ORM queries loads **2x faster**
66
+ through the toolbar (0.60 s → 0.30 s, the rest being the queries themselves and the templates).
67
+ Measured with [`bench/django_toolbar.py`](bench/django_toolbar.py), Django 6.1, django-debug-toolbar 8.0,
68
+ Python 3.13.
69
+ - **Migrations** with `RunSQL` scripts and `sqlmigrate` go through `sqlparse.split` and `sqlparse.format`.
70
+ - **Tests**: the runner formats debug SQL with `sqlparse.format`.
71
+
55
72
  ## Results
56
73
 
74
+ <p align="center">
75
+ <img src="https://raw.githubusercontent.com/fullfud/sqlparse-turbo/main/docs/assets/speed.svg" alt="Seconds for 400 SQL queries, one call per file, Python 3.13: split 0.93 s against 0.008 s (113x), format with keyword_case 0.99 s against 0.019 s (53x), format with reindent 3.68 s against 0.121 s (30x), parse 2.96 s against 0.175 s (17x)." width="760">
76
+ </p>
77
+
78
+ The chart and the animation above come from [`bench/race_times.py`](bench/race_times.py) (best of 3 per file,
79
+ every result checked equal) and [`tools/make_visuals.py`](tools/make_visuals.py).
80
+
57
81
  The whole benchmark corpus (440 files, 2.1 MB of SQL: generated queries and scripts), sqlparse 0.6.1 against
58
82
  `sqlparse_turbo` through the same public calls, CPython 3.11, Windows 11, best of 3, every result checked equal
59
83
  ([`bench/bench_package.py`](bench/bench_package.py)):
@@ -112,6 +136,8 @@ Unicode versions (see Unicode versions below).
112
136
  | 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
137
  | 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
138
  | 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 |
139
+ | Callers' own filter stacks through `FilterStack.run` (`check_package.py stacks`; `check_recursion.py package`): grouping only, the indent filters, a filter of the caller's own, serializers | same trees and output as sqlparse's run, the recursion error from exactly the same size |
140
+ | Other sqlparse versions (`check_other_sqlparse.py`, in CI with 0.4.4, 0.5.3, 0.6.0) | every call answered by that sqlparse, nothing reaches the Rust |
115
141
  | 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
142
  | 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
143
  | 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 |
@@ -120,9 +146,20 @@ Unicode versions (see Unicode versions below).
120
146
  ## Install
121
147
 
122
148
  ```sh
123
- pip install sqlparse-turbo # pulls sqlparse==0.6.1, installs sqlparse_turbo and the sqlformat-turbo command
149
+ pip install sqlparse-turbo "sqlparse==0.6.1" # sqlparse_turbo, the sqlformat-turbo command, and sqlparse 0.6.1
150
+ ```
151
+
152
+ Only sqlparse 0.6.1 gets the Rust. The package does not require that version (requiring it would stop a project
153
+ pinned to another sqlparse from installing it at all), so pip keeps whatever sqlparse a project already has. On
154
+ another version everything works as plain sqlparse, no faster, and the import warns:
155
+
156
+ ```
157
+ RuntimeWarning: sqlparse_turbo runs in Rust only with sqlparse 0.6.1; sqlparse 0.5.3 is installed, so every call
158
+ goes to sqlparse at its own speed (pip install "sqlparse==0.6.1")
124
159
  ```
125
160
 
161
+ `sqlparse_turbo.ACTIVE` tells which it is.
162
+
126
163
  Wheels are built for Linux x86_64 and aarch64, Windows x64 and macOS (arm64 and Intel), one abi3 wheel each for
127
164
  every CPython from 3.10 on. Elsewhere pip builds from the source distribution, which needs a Rust toolchain.
128
165
 
@@ -152,6 +189,11 @@ sqlparse's own token type objects, and only for the default lexer as sqlparse se
152
189
  takes. A name bound before with `from sqlparse import format` keeps the original. `uninstall()` puts sqlparse's
153
190
  functions back. `install()` refuses (returns False) if the installed sqlparse is not 0.6.1.
154
191
 
192
+ `install()` also replaces `FilterStack.run`, which callers use to run their own sqlparse filters
193
+ (django-debug-toolbar's SQL panel): a stack with grouping on and no token-stream filters gets its statements
194
+ grouped in Rust, as `parse()` makes them, and runs its own statement filters and serializers on them in Python.
195
+ Any other stack runs as sqlparse's.
196
+
155
197
  `sqlformat-turbo` (or `python -m sqlparse_turbo`) is sqlparse's `sqlformat`, same arguments, output and exit codes.
156
198
 
157
199
  ### When the Rust runs, and when sqlparse does
@@ -294,6 +336,9 @@ whole statement for every line) are walked backwards to the last line break in t
294
336
  that big, so the package gives `indent_width` above 4096 to sqlparse.
295
337
  - **A call the package hands to sqlparse** has the package's frame on the stack as well, so sqlparse's own
296
338
  recursion limit comes one nesting level sooner than when called directly.
339
+ - **`FilterStack.run` with `install()`** decides between the Rust and sqlparse's own run when it is called;
340
+ sqlparse's reads the stack's filters when the first statement is asked for, so a filter added to the stack
341
+ after `run()` was called but before iterating is not seen.
297
342
  - **The `RecursionError` behind the recursion `SQLParseError`** says `maximum recursion depth exceeded`. On
298
343
  CPython 3.10 sqlparse's says where Python hit the limit as well (`... in comparison`, `... in
299
344
  __instancecheck__`), which depends on the C call sqlparse was in; the `SQLParseError` itself is the same.
@@ -346,4 +391,3 @@ front door, and most of the Rust is the generated Unicode and lexer tables.
346
391
 
347
392
  BSD-3-Clause, like sqlparse ([`LICENSE`](LICENSE)). The port follows sqlparse's code closely, so sqlparse's
348
393
  copyright notice is kept next to ours.
349
-
@@ -4,12 +4,13 @@ build-backend = "maturin"
4
4
 
5
5
  [project]
6
6
  name = "sqlparse-turbo"
7
- version = "0.1.0"
8
- description = "sqlparse's format(), split() and parse() rewritten in Rust: same output, byte for byte, many times faster"
7
+ version = "0.1.1"
8
+ description = "sqlparse 0.6.1's format(), split() and parse() rewritten in Rust: same output, byte for byte, many times faster"
9
9
  readme = "README.md"
10
10
  license = "BSD-3-Clause"
11
11
  requires-python = ">=3.10"
12
- dependencies = ["sqlparse==0.6.1"]
12
+ # Runs in Rust with sqlparse 0.6.1; with any other version every call is sqlparse's own (see the README)
13
+ dependencies = ["sqlparse>=0.4"]
13
14
  keywords = ["sql", "sqlparse", "formatter", "parser", "rust"]
14
15
  classifiers = [
15
16
  "Development Status :: 4 - Beta",
@@ -17,6 +18,12 @@ classifiers = [
17
18
  "Operating System :: OS Independent",
18
19
  "Programming Language :: Python :: 3",
19
20
  "Programming Language :: Python :: 3 :: Only",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Programming Language :: Python :: 3.14",
26
+ "Framework :: Django",
20
27
  "Programming Language :: Python :: Implementation :: CPython",
21
28
  "Programming Language :: Rust",
22
29
  "Topic :: Database",
@@ -10,12 +10,14 @@
10
10
  # that looks them up on the module (sqlparse.format(...)); a name bound earlier
11
11
  # with `from sqlparse import format` keeps the original. sqlparse's default
12
12
  # lexer gets the Rust tokenizer too, so sqlparse.parse() and everything else
13
- # that lexes runs it.
13
+ # that lexes runs it, and FilterStack.run (callers' own filter stacks, as
14
+ # django-debug-toolbar's) gets its statements grouped in Rust.
14
15
 
15
16
  The Rust is a port of sqlparse 0.6.1 checked call by call against it (see the project's README). A call goes to
16
17
  the original sqlparse, unchanged, unless all of this holds:
17
18
 
18
- - the installed sqlparse is 0.6.1;
19
+ - the installed sqlparse is 0.6.1 (with any other version every call goes to sqlparse, and install() does
20
+ nothing);
19
21
  - `sql` is a `str` (not bytes, not a stream, not a subclass); `encoding` is then not used, as in sqlparse,
20
22
  which only decodes bytes with it;
21
23
  - sqlparse's default lexer is as sqlparse sets it up (no add_keywords, set_SQL_REGEX, clear), and nothing in
@@ -59,7 +61,7 @@ from . import _native
59
61
  from ._unicode_drift import DRIFT as _DRIFT
60
62
  from ._unicode_drift import PORTED_UNICODE as _PORTED_UNICODE
61
63
 
62
- __all__ = ['format', 'split', 'split_many', 'parse', 'install', 'uninstall', 'PORTED_VERSION']
64
+ __all__ = ['format', 'split', 'split_many', 'parse', 'install', 'uninstall', 'PORTED_VERSION', 'ACTIVE']
63
65
 
64
66
  PORTED_VERSION = '0.6.1'
65
67
 
@@ -67,7 +69,20 @@ _original_format = sqlparse.format
67
69
  _original_split = sqlparse.split
68
70
  _original_parse = sqlparse.parse
69
71
  _original_get_tokens = _lexer.Lexer.get_tokens
72
+ _original_run = sqlparse.engine.filter_stack.FilterStack.run
70
73
  _ported = sqlparse.__version__ == PORTED_VERSION
74
+ # Whether the Rust runs at all: only with the sqlparse version it was ported from. Otherwise every call is
75
+ # sqlparse's own, at its own speed.
76
+ ACTIVE = _ported
77
+ if not _ported:
78
+ import warnings as _warnings
79
+
80
+ _warnings.warn(
81
+ f'sqlparse_turbo runs in Rust only with sqlparse {PORTED_VERSION}; sqlparse {sqlparse.__version__} is '
82
+ f'installed, so every call goes to sqlparse at its own speed (pip install "sqlparse=={PORTED_VERSION}")',
83
+ RuntimeWarning,
84
+ stacklevel=2,
85
+ )
71
86
 
72
87
 
73
88
 
@@ -234,7 +249,14 @@ def split(sql, encoding=None, strip_semicolon=False):
234
249
  return _native.split(sql, strip_semicolon)
235
250
  except UnicodeEncodeError:
236
251
  pass
237
- return _original_split(sql, encoding, strip_semicolon)
252
+ return _sqlparse_split(sql, encoding, strip_semicolon)
253
+
254
+
255
+ def _sqlparse_split(sql, encoding, strip_semicolon):
256
+ # sqlparse before 0.5 has no strip_semicolon: left out unless asked for, as a direct call would
257
+ if strip_semicolon is False:
258
+ return _original_split(sql, encoding)
259
+ return _original_split(sql, encoding, strip_semicolon=strip_semicolon)
238
260
 
239
261
 
240
262
  def split_many(sqls, encoding=None, strip_semicolon=False):
@@ -252,7 +274,7 @@ def split_many(sqls, encoding=None, strip_semicolon=False):
252
274
  pass
253
275
  for i, statements in enumerate(out):
254
276
  if statements is None:
255
- out[i] = _original_split(sqls[i], encoding, strip_semicolon)
277
+ out[i] = _sqlparse_split(sqls[i], encoding, strip_semicolon)
256
278
  return out
257
279
 
258
280
 
@@ -263,11 +285,12 @@ def _token_type(name):
263
285
  return t
264
286
 
265
287
 
266
- _native.set_token_types({name: _token_type(name) for name in _native.token_type_names()})
267
- _native.set_sql_objects(
268
- {name: cls for name, cls in vars(_sql).items() if isinstance(cls, type) and issubclass(cls, _sql.Token)},
269
- object.__new__,
270
- )
288
+ if _ported:
289
+ _native.set_token_types({name: _token_type(name) for name in _native.token_type_names()})
290
+ _native.set_sql_objects(
291
+ {name: cls for name, cls in vars(_sql).items() if isinstance(cls, type) and issubclass(cls, _sql.Token)},
292
+ object.__new__,
293
+ )
271
294
 
272
295
 
273
296
  def parse(sql, encoding=None):
@@ -306,6 +329,46 @@ def _get_tokens(self, text, encoding=None):
306
329
  yield from _original_get_tokens(self, text, encoding)
307
330
 
308
331
 
332
+ def _run(self, sql, encoding=None):
333
+ """sqlparse's FilterStack.run, with install(): a stack with grouping on and no token-stream filters gets its
334
+ statements grouped in Rust (the objects parse() returns, as sqlparse's own run has them at that point) and runs
335
+ its statement filters and serializers on them in Python. Anything else gets sqlparse's own run, returned as
336
+ is (no frame of ours under it). Which one is decided here, when run() is called; sqlparse's reads the stack's
337
+ filters when the first statement is asked for, so a filter added in between is the one difference."""
338
+ if self._grouping and not self.preprocess and type(sql) is str and _text_ported(sql) and _sqlparse_untouched():
339
+ return _run_grouped(self, sql, encoding)
340
+ return _original_run(self, sql, encoding)
341
+
342
+
343
+ def _run_grouped(self, sql, encoding):
344
+ # a generator, as sqlparse's run: nothing happens until the first statement is asked for
345
+ too_deep = False
346
+ statements = None
347
+ try:
348
+ # Called from this generator, which stands where sqlparse's run stands: the Rust counts it so.
349
+ statements = _native.parse(sql, True)
350
+ except UnicodeEncodeError:
351
+ pass
352
+ except _SQLParseError as err:
353
+ if err.args != (_RECURSION,):
354
+ raise
355
+ too_deep = True
356
+ if too_deep:
357
+ _raise_recursion()
358
+ if statements is None:
359
+ yield from _original_run(self, sql, encoding)
360
+ return
361
+ try:
362
+ for stmt in statements:
363
+ for filter_ in self.stmtprocess:
364
+ filter_.process(stmt)
365
+ for filter_ in self.postprocess:
366
+ stmt = filter_.process(stmt)
367
+ yield stmt
368
+ except RecursionError as err:
369
+ raise _SQLParseError(_RECURSION) from err
370
+
371
+
309
372
  # Everything of sqlparse the Rust reproduces: its modules' names and its classes' attributes, as imported. Where
310
373
  # install() puts the package's own function, that one is allowed as well.
311
374
  _WATCHED_MODULES = [
@@ -317,6 +380,7 @@ _WATCHED_MODULES = [
317
380
  _INSTALLED = {
318
381
  (sqlparse, 'format'): format, (sqlparse, 'split'): split, (sqlparse, 'parse'): parse,
319
382
  (_lexer.Lexer, 'get_tokens'): _get_tokens,
383
+ (sqlparse.engine.filter_stack.FilterStack, 'run'): _run,
320
384
  }
321
385
 
322
386
 
@@ -347,7 +411,7 @@ def _watch():
347
411
  return [namespace for namespace, _, _ in watch]
348
412
 
349
413
 
350
- _watched_dicts = _watch()
414
+ _watched_dicts = _watch() if _ported else []
351
415
 
352
416
  # Comparing every watched name costs a few microseconds a call. CPython 3.12+ can tell us instead when one of
353
417
  # these dicts changes (a dict watcher): the comparison then runs once after a change, not on every call. On
@@ -400,7 +464,7 @@ def _add_watchers(dicts):
400
464
  return True
401
465
 
402
466
 
403
- _watching = _add_watchers(_watched_dicts)
467
+ _watching = _add_watchers(_watched_dicts) if _ported else False
404
468
 
405
469
 
406
470
  def _sqlparse_untouched():
@@ -424,6 +488,7 @@ def install():
424
488
  sqlparse.split = split
425
489
  sqlparse.parse = parse
426
490
  _lexer.Lexer.get_tokens = _get_tokens
491
+ sqlparse.engine.filter_stack.FilterStack.run = _run
427
492
  return True
428
493
 
429
494
 
@@ -433,3 +498,4 @@ def uninstall():
433
498
  sqlparse.split = _original_split
434
499
  sqlparse.parse = _original_parse
435
500
  _lexer.Lexer.get_tokens = _original_get_tokens
501
+ sqlparse.engine.filter_stack.FilterStack.run = _original_run
@@ -313,14 +313,19 @@ fn set_sql_objects(
313
313
  Ok(())
314
314
  }
315
315
 
316
- /// `parse`: `sqlparse.parse(sql)`, grouped in Rust, as a tuple of sqlparse's own `Statement` objects.
316
+ /// `parse`: `sqlparse.parse(sql)`, grouped in Rust, as a tuple of sqlparse's own `Statement` objects. With
317
+ /// `run`, the recursion limit is counted as for sqlparse's `FilterStack.run` (called from the package's).
317
318
  #[pyfunction]
318
- #[pyo3(name = "parse", signature = (sql))]
319
- fn parse<'py>(py: Python<'py>, sql: String) -> PyResult<Bound<'py, pyo3::types::PyTuple>> {
319
+ #[pyo3(name = "parse", signature = (sql, run=false))]
320
+ fn parse<'py>(
321
+ py: Python<'py>,
322
+ sql: String,
323
+ run: bool,
324
+ ) -> PyResult<Bound<'py, pyo3::types::PyTuple>> {
320
325
  let objects = SQL_OBJECTS.get().ok_or_else(|| {
321
326
  pyo3::exceptions::PyRuntimeError::new_err("parse: set_sql_objects was not called")
322
327
  })?;
323
- let parsed = port::parse_trees(&sql).map_err(error)?;
328
+ let parsed = port::parse_trees(&sql, run).map_err(error)?;
324
329
  let statements = parsed.to_python(py, objects);
325
330
  pyo3::types::PyTuple::new(py, statements?)
326
331
  }
@@ -42,11 +42,23 @@ pub fn token_type_names() -> Vec<&'static str> {
42
42
  /// The recursion limit is counted as for `sqlparse.parse` called where the package's `parse` stands.
43
43
  pub struct Parsed(Vec<tree::Tree>);
44
44
 
45
- /// See [`Parsed`].
46
- pub fn parse_trees(sql: &str) -> Result<Parsed, String> {
47
- format::parse(sql, &python_stack(PARSE_ENTRY_FRAMES_311)).map(Parsed)
45
+ /// See [`Parsed`]. With `run`, the recursion limit is counted as for sqlparse's `FilterStack.run` generator,
46
+ /// whose frame the caller's stands in for (the package's replacement of it): no `parse` frame above it, and on
47
+ /// up to 3.11 no `tuple()` C call either.
48
+ pub fn parse_trees(sql: &str, run: bool) -> Result<Parsed, String> {
49
+ let stack = if run {
50
+ python_stack_from(PARSE_ENTRY_FRAMES_311, RUN_FRAMES_311, RUN_FRAMES_312)
51
+ } else {
52
+ python_stack(PARSE_ENTRY_FRAMES_311)
53
+ };
54
+ format::parse(sql, &stack).map(Parsed)
48
55
  }
49
56
 
57
+ /// What `sqlparse.parse` has on the stack above `FilterStack.run`'s frame that a call from `run` itself has not,
58
+ /// by version (the `tuple()` C call counts up to 3.11 only). Measured with tools/check_recursion.py package.
59
+ const RUN_FRAMES_311: usize = 1;
60
+ const RUN_FRAMES_312: usize = 1;
61
+
50
62
  /// What `Parsed::to_python` needs from `sqlparse`: its `sql` classes by name, its token types by `str()`,
51
63
  /// and `object.__new__`.
52
64
  pub struct SqlObjects {
@@ -298,6 +310,16 @@ const PARSE_ENTRY_FRAMES_311: usize = 1;
298
310
  /// `sqlparse.format`'s (already counted in the entry point), there is neither, so two frames come off.
299
311
  /// `entry_frames_311` is FORMAT_ENTRY_FRAMES_311 or PARSE_ENTRY_FRAMES_311, for the entry point being run.
300
312
  fn python_stack(entry_frames_311: usize) -> grouping::Stack {
313
+ python_stack_from(entry_frames_311, 0, 0)
314
+ }
315
+
316
+ /// [`python_stack`], with `fewer_311` / `fewer_312` frames less above the caller than the entry point has (up to
317
+ /// 3.11 / from 3.12).
318
+ fn python_stack_from(
319
+ entry_frames_311: usize,
320
+ fewer_311: usize,
321
+ fewer_312: usize,
322
+ ) -> grouping::Stack {
301
323
  use pyo3::prelude::*;
302
324
  pyo3::Python::attach(|py| -> Option<grouping::Stack> {
303
325
  let sys = py.import("sys").ok()?;
@@ -322,7 +344,9 @@ fn python_stack(entry_frames_311: usize) -> grouping::Stack {
322
344
  .extract()
323
345
  .ok()?;
324
346
  if minor >= 12 {
325
- shift += entry_frames_311 - 1;
347
+ shift += entry_frames_311 - 1 + fewer_312;
348
+ } else {
349
+ shift += fewer_311;
326
350
  }
327
351
  let mut depth = 1;
328
352
  loop {
File without changes