singlestore-sql-validator 0.0.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.
- singlestore_sql_validator-0.0.1/LICENSE +201 -0
- singlestore_sql_validator-0.0.1/PKG-INFO +128 -0
- singlestore_sql_validator-0.0.1/README.md +106 -0
- singlestore_sql_validator-0.0.1/pyproject.toml +38 -0
- singlestore_sql_validator-0.0.1/sql_validator/__init__.py +13 -0
- singlestore_sql_validator-0.0.1/sql_validator/connection.py +14 -0
- singlestore_sql_validator-0.0.1/sql_validator/result.py +100 -0
- singlestore_sql_validator-0.0.1/sql_validator/validator.py +329 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: singlestore-sql-validator
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: SQL grammar validator for SingleStore queries
|
|
5
|
+
License: Apache License (2.0)
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Author: Volodymyr Tkachuk
|
|
8
|
+
Author-email: vtkachuk-ua@singlestore.com
|
|
9
|
+
Requires-Python: >=3.10,<4.0
|
|
10
|
+
Classifier: License :: Other/Proprietary License
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Requires-Dist: websockets (>=16.0,<17.0)
|
|
18
|
+
Project-URL: Homepage, https://github.com/singlestore-labs/sql-validator-python
|
|
19
|
+
Project-URL: Issues, https://github.com/singlestore-labs/sql-validator-python/issues
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# sql-validator-python
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
`sql-validator-python` is a Python library for validating SQL queries using the SingleStore Language Server (version 0.1.3 and later). It provides a convenient interface to check SQL syntax and semantics by communicating with a SingleStore language server instance over TCP or WebSocket (with optional TLS support).
|
|
26
|
+
|
|
27
|
+
## Features
|
|
28
|
+
|
|
29
|
+
- Validate SQL queries for correctness using SingleStore's language server
|
|
30
|
+
- Supports TCP, WS, and WSS (WebSocket Secure) connections
|
|
31
|
+
- Flexible connection configuration (host/port or connection string)
|
|
32
|
+
- TLS/SSL support for secure connections
|
|
33
|
+
- Returns detailed validation results, including error tokens and suggestions
|
|
34
|
+
|
|
35
|
+
## Installation
|
|
36
|
+
|
|
37
|
+
Install via pip (after cloning or packaging):
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install sql-validator-python
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Or add to your `pyproject.toml` as a dependency.
|
|
44
|
+
|
|
45
|
+
## Usage
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from sql_validator import Validator, ConnectionMode
|
|
49
|
+
|
|
50
|
+
# Example: Connect using TCP
|
|
51
|
+
validator = Validator(
|
|
52
|
+
connection_mode=ConnectionMode.TCP,
|
|
53
|
+
server_host="localhost",
|
|
54
|
+
server_port=9000
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
# Example: Connect using a connection string
|
|
58
|
+
# validator = Validator(connection_string="tcp://localhost:9000")
|
|
59
|
+
|
|
60
|
+
result = validator.validate("SELECT * FROM my_table;")
|
|
61
|
+
if result.is_valid:
|
|
62
|
+
print("Query is valid!")
|
|
63
|
+
else:
|
|
64
|
+
print(f"Error: {result.error_token} at {result.error_token_position}")
|
|
65
|
+
if result.alternative_tokens:
|
|
66
|
+
print("Suggestions:", result.alternative_tokens)
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## API
|
|
70
|
+
|
|
71
|
+
### `Validator`
|
|
72
|
+
|
|
73
|
+
#### Initialization
|
|
74
|
+
|
|
75
|
+
You can initialize a `Validator` in two ways:
|
|
76
|
+
|
|
77
|
+
- By specifying `connection_mode`, `server_host`, and `server_port`:
|
|
78
|
+
- `connection_mode`: `ConnectionMode.TCP`, `ConnectionMode.WS`, or `ConnectionMode.WSS`
|
|
79
|
+
- `server_host`: Hostname of the language server
|
|
80
|
+
- `server_port`: Port number
|
|
81
|
+
- `tls`: Enable TLS (for WSS or secure TCP)
|
|
82
|
+
- `tls_ca_file`: Path to CA certificate (optional)
|
|
83
|
+
- `tls_insecure_skip_verify`: Skip TLS verification (optional)
|
|
84
|
+
|
|
85
|
+
- By providing a `connection_string` (e.g., `tcp://localhost:9000`, `ws://host:port`, `wss://host:port`)
|
|
86
|
+
|
|
87
|
+
#### Methods
|
|
88
|
+
|
|
89
|
+
- `validate(query: str, version: str = "") -> ValidationResult`
|
|
90
|
+
- Validates the given SQL query.
|
|
91
|
+
- `version` (optional): Database version string (format: `major.minor.build`, or empty/"default").
|
|
92
|
+
- Returns a `ValidationResult` object.
|
|
93
|
+
|
|
94
|
+
#### Static Methods
|
|
95
|
+
|
|
96
|
+
- `_validate_version(version: str) -> bool`
|
|
97
|
+
- Checks if the version string matches the required pattern (`major.minor.build`).
|
|
98
|
+
|
|
99
|
+
### `ValidationResult`
|
|
100
|
+
|
|
101
|
+
- `is_valid`: `bool` — Whether the query is valid
|
|
102
|
+
- `error_token`: `Optional[str]` — The token that caused the error (if any)
|
|
103
|
+
- `error_token_position`: `Optional[TokenPosition]` — Position of the error token
|
|
104
|
+
- `alternative_tokens`: `Optional[CompletionList]` — Suggestions for fixing the error
|
|
105
|
+
|
|
106
|
+
## Example
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
from sql_validator import Validator
|
|
110
|
+
validator = Validator(connection_string="tcp://localhost:9000")
|
|
111
|
+
result = validator.validate("SELECT foo FROM bar;")
|
|
112
|
+
if result.is_valid:
|
|
113
|
+
print("Valid!")
|
|
114
|
+
else:
|
|
115
|
+
print("Invalid SQL:", result.error_token)
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
## Notes
|
|
120
|
+
|
|
121
|
+
- This library is intended to be used with a running SingleStore Language Server instance (version 0.1.3 or later).
|
|
122
|
+
- It does not start or manage the server process itself.
|
|
123
|
+
- Documentation for the SingleStore Language Server can be found at: [https://github.com/singlestore-labs/language-server](https://github.com/singlestore-labs/language-server)
|
|
124
|
+
|
|
125
|
+
## License
|
|
126
|
+
|
|
127
|
+
This project is licensed under the terms of the Apache License, Version 2.0.
|
|
128
|
+
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
# sql-validator-python
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
`sql-validator-python` is a Python library for validating SQL queries using the SingleStore Language Server (version 0.1.3 and later). It provides a convenient interface to check SQL syntax and semantics by communicating with a SingleStore language server instance over TCP or WebSocket (with optional TLS support).
|
|
5
|
+
|
|
6
|
+
## Features
|
|
7
|
+
|
|
8
|
+
- Validate SQL queries for correctness using SingleStore's language server
|
|
9
|
+
- Supports TCP, WS, and WSS (WebSocket Secure) connections
|
|
10
|
+
- Flexible connection configuration (host/port or connection string)
|
|
11
|
+
- TLS/SSL support for secure connections
|
|
12
|
+
- Returns detailed validation results, including error tokens and suggestions
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
Install via pip (after cloning or packaging):
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pip install sql-validator-python
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Or add to your `pyproject.toml` as a dependency.
|
|
23
|
+
|
|
24
|
+
## Usage
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
from sql_validator import Validator, ConnectionMode
|
|
28
|
+
|
|
29
|
+
# Example: Connect using TCP
|
|
30
|
+
validator = Validator(
|
|
31
|
+
connection_mode=ConnectionMode.TCP,
|
|
32
|
+
server_host="localhost",
|
|
33
|
+
server_port=9000
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
# Example: Connect using a connection string
|
|
37
|
+
# validator = Validator(connection_string="tcp://localhost:9000")
|
|
38
|
+
|
|
39
|
+
result = validator.validate("SELECT * FROM my_table;")
|
|
40
|
+
if result.is_valid:
|
|
41
|
+
print("Query is valid!")
|
|
42
|
+
else:
|
|
43
|
+
print(f"Error: {result.error_token} at {result.error_token_position}")
|
|
44
|
+
if result.alternative_tokens:
|
|
45
|
+
print("Suggestions:", result.alternative_tokens)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## API
|
|
49
|
+
|
|
50
|
+
### `Validator`
|
|
51
|
+
|
|
52
|
+
#### Initialization
|
|
53
|
+
|
|
54
|
+
You can initialize a `Validator` in two ways:
|
|
55
|
+
|
|
56
|
+
- By specifying `connection_mode`, `server_host`, and `server_port`:
|
|
57
|
+
- `connection_mode`: `ConnectionMode.TCP`, `ConnectionMode.WS`, or `ConnectionMode.WSS`
|
|
58
|
+
- `server_host`: Hostname of the language server
|
|
59
|
+
- `server_port`: Port number
|
|
60
|
+
- `tls`: Enable TLS (for WSS or secure TCP)
|
|
61
|
+
- `tls_ca_file`: Path to CA certificate (optional)
|
|
62
|
+
- `tls_insecure_skip_verify`: Skip TLS verification (optional)
|
|
63
|
+
|
|
64
|
+
- By providing a `connection_string` (e.g., `tcp://localhost:9000`, `ws://host:port`, `wss://host:port`)
|
|
65
|
+
|
|
66
|
+
#### Methods
|
|
67
|
+
|
|
68
|
+
- `validate(query: str, version: str = "") -> ValidationResult`
|
|
69
|
+
- Validates the given SQL query.
|
|
70
|
+
- `version` (optional): Database version string (format: `major.minor.build`, or empty/"default").
|
|
71
|
+
- Returns a `ValidationResult` object.
|
|
72
|
+
|
|
73
|
+
#### Static Methods
|
|
74
|
+
|
|
75
|
+
- `_validate_version(version: str) -> bool`
|
|
76
|
+
- Checks if the version string matches the required pattern (`major.minor.build`).
|
|
77
|
+
|
|
78
|
+
### `ValidationResult`
|
|
79
|
+
|
|
80
|
+
- `is_valid`: `bool` — Whether the query is valid
|
|
81
|
+
- `error_token`: `Optional[str]` — The token that caused the error (if any)
|
|
82
|
+
- `error_token_position`: `Optional[TokenPosition]` — Position of the error token
|
|
83
|
+
- `alternative_tokens`: `Optional[CompletionList]` — Suggestions for fixing the error
|
|
84
|
+
|
|
85
|
+
## Example
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
from sql_validator import Validator
|
|
89
|
+
validator = Validator(connection_string="tcp://localhost:9000")
|
|
90
|
+
result = validator.validate("SELECT foo FROM bar;")
|
|
91
|
+
if result.is_valid:
|
|
92
|
+
print("Valid!")
|
|
93
|
+
else:
|
|
94
|
+
print("Invalid SQL:", result.error_token)
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
## Notes
|
|
99
|
+
|
|
100
|
+
- This library is intended to be used with a running SingleStore Language Server instance (version 0.1.3 or later).
|
|
101
|
+
- It does not start or manage the server process itself.
|
|
102
|
+
- Documentation for the SingleStore Language Server can be found at: [https://github.com/singlestore-labs/language-server](https://github.com/singlestore-labs/language-server)
|
|
103
|
+
|
|
104
|
+
## License
|
|
105
|
+
|
|
106
|
+
This project is licensed under the terms of the Apache License, Version 2.0.
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "singlestore-sql-validator"
|
|
3
|
+
version = "0.0.1"
|
|
4
|
+
description = "SQL grammar validator for SingleStore queries"
|
|
5
|
+
authors = [
|
|
6
|
+
{name = "Volodymyr Tkachuk",email = "vtkachuk-ua@singlestore.com"}
|
|
7
|
+
]
|
|
8
|
+
license = {text = "Apache License (2.0)"}
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
|
|
11
|
+
dependencies = [
|
|
12
|
+
"websockets (>=16.0,<17.0)",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
[project.urls]
|
|
16
|
+
Homepage = "https://github.com/singlestore-labs/sql-validator-python"
|
|
17
|
+
Issues = "https://github.com/singlestore-labs/sql-validator-python/issues"
|
|
18
|
+
|
|
19
|
+
[tool.poetry]
|
|
20
|
+
name = "singlestore-sql-validator"
|
|
21
|
+
packages = [{include = "sql_validator"}]
|
|
22
|
+
|
|
23
|
+
[build-system]
|
|
24
|
+
requires = ["poetry-core>=2.0.0,<3.0.0"]
|
|
25
|
+
build-backend = "poetry.core.masonry.api"
|
|
26
|
+
|
|
27
|
+
[tool.poetry.dependencies]
|
|
28
|
+
python = ">=3.10,<4.0"
|
|
29
|
+
|
|
30
|
+
[tool.poetry.group.test.dependencies]
|
|
31
|
+
pytest = "^9.0.3"
|
|
32
|
+
docker = "^7.1.0"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
[tool.poetry.group.dev.dependencies]
|
|
36
|
+
codespell = "^2.4.1"
|
|
37
|
+
ruff = "^0.11.9"
|
|
38
|
+
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from .validator import Validator
|
|
2
|
+
from .result import ValidationResult, TokenPosition, CompletionItem, CompletionList
|
|
3
|
+
from .connection import ConnectionMode
|
|
4
|
+
|
|
5
|
+
# Expose the main classes in the package
|
|
6
|
+
__all__ = [
|
|
7
|
+
"ConnectionMode",
|
|
8
|
+
"Validator",
|
|
9
|
+
"ValidationResult",
|
|
10
|
+
"TokenPosition",
|
|
11
|
+
"CompletionItem",
|
|
12
|
+
"CompletionList",
|
|
13
|
+
]
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from enum import Enum
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ConnectionMode(Enum):
|
|
5
|
+
"""
|
|
6
|
+
Defines the connection modes for the SQL validator.
|
|
7
|
+
- TCP: Standard TCP connection.
|
|
8
|
+
- WS: WebSocket connection without TLS.
|
|
9
|
+
- WSS: WebSocket connection with TLS (must have TLS enabled).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
TCP = "tcp"
|
|
13
|
+
WS = "ws"
|
|
14
|
+
WSS = "wss"
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from typing import Any, Dict, List, Optional
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
@dataclass(frozen=True)
|
|
6
|
+
class TokenPosition:
|
|
7
|
+
"""
|
|
8
|
+
Represents the position of a token in the SQL query.
|
|
9
|
+
- line: The line number where the token is located (0-based).
|
|
10
|
+
- character: The character offset within the line where the token starts (0-based).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
line: int
|
|
14
|
+
character: int
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class CompletionItem:
|
|
19
|
+
"""
|
|
20
|
+
Represents a completion item for an SQL query.
|
|
21
|
+
- label: The label of the completion item.
|
|
22
|
+
- insert_text: The text to be inserted when the completion item is selected.
|
|
23
|
+
- detail: Additional details about the completion item.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
label: str
|
|
27
|
+
insert_text: str
|
|
28
|
+
detail: str
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class CompletionList:
|
|
33
|
+
"""
|
|
34
|
+
Represents a list of completion items for an SQL query.
|
|
35
|
+
- is_incomplete: Indicates if the list is incomplete.
|
|
36
|
+
- items: The list of completion items.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
is_incomplete: bool
|
|
40
|
+
items: List[CompletionItem]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class ValidationResult:
|
|
45
|
+
"""
|
|
46
|
+
Represents the result of validating an SQL query.
|
|
47
|
+
- is_valid: Indicates if the SQL query is valid.
|
|
48
|
+
- error_token: The token that caused the validation error, if any.
|
|
49
|
+
- error_token_position: The position of the error token, if any.
|
|
50
|
+
- alternative_tokens: A list of alternative tokens that could be used to fix the error, if any.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
is_valid: bool
|
|
54
|
+
error_token: Optional[str] = None
|
|
55
|
+
error_token_position: Optional[TokenPosition] = None
|
|
56
|
+
alternative_tokens: Optional[CompletionList] = None
|
|
57
|
+
|
|
58
|
+
@classmethod
|
|
59
|
+
def from_json(cls, resp: Dict[str, Any]) -> "ValidationResult":
|
|
60
|
+
"""
|
|
61
|
+
Creates a ValidationResult instance from a JSON-RPC response.
|
|
62
|
+
- resp: The JSON-RPC response containing the validation result.
|
|
63
|
+
- Returns: A ValidationResult instance populated with the data from the response.
|
|
64
|
+
"""
|
|
65
|
+
result = resp.get("result", {})
|
|
66
|
+
is_valid = result.get("isValid", False)
|
|
67
|
+
error_token = result.get("errorToken")
|
|
68
|
+
|
|
69
|
+
error_token_position = None
|
|
70
|
+
if "errorTokenPosition" in result and result["errorTokenPosition"] is not None:
|
|
71
|
+
pos = result["errorTokenPosition"]
|
|
72
|
+
error_token_position = TokenPosition(
|
|
73
|
+
line=pos.get("line", 0), character=pos.get("character", 0)
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
alternative_tokens = None
|
|
77
|
+
if "alternativeTokens" in result and result["alternativeTokens"] is not None:
|
|
78
|
+
alt = result["alternativeTokens"]
|
|
79
|
+
items = []
|
|
80
|
+
items_data = alt.get("items", [])
|
|
81
|
+
if not items_data:
|
|
82
|
+
items_data = []
|
|
83
|
+
for item in items_data:
|
|
84
|
+
items.append(
|
|
85
|
+
CompletionItem(
|
|
86
|
+
label=item.get("label", ""),
|
|
87
|
+
insert_text=item.get("insertText", ""),
|
|
88
|
+
detail=item.get("detail", ""),
|
|
89
|
+
)
|
|
90
|
+
)
|
|
91
|
+
alternative_tokens = CompletionList(
|
|
92
|
+
is_incomplete=alt.get("isIncomplete", False), items=items
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
return cls(
|
|
96
|
+
is_valid=is_valid,
|
|
97
|
+
error_token=error_token,
|
|
98
|
+
error_token_position=error_token_position,
|
|
99
|
+
alternative_tokens=alternative_tokens,
|
|
100
|
+
)
|
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
from urllib.parse import urlparse
|
|
3
|
+
from abc import ABC
|
|
4
|
+
from .connection import ConnectionMode
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import asyncio
|
|
8
|
+
import socket
|
|
9
|
+
import ssl
|
|
10
|
+
import re
|
|
11
|
+
import websockets
|
|
12
|
+
|
|
13
|
+
from .result import ValidationResult
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Validator(ABC):
|
|
17
|
+
"""
|
|
18
|
+
Validator class to validate SQL queries against a SingleStore language server.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
*,
|
|
24
|
+
connection_string: Optional[str] = None,
|
|
25
|
+
connection_mode: ConnectionMode = ConnectionMode.TCP,
|
|
26
|
+
server_host: Optional[str] = None,
|
|
27
|
+
server_port: Optional[int] = None,
|
|
28
|
+
tls: bool = False,
|
|
29
|
+
tls_ca_file: Optional[str] = None,
|
|
30
|
+
tls_insecure_skip_verify: Optional[bool] = None,
|
|
31
|
+
**kwargs,
|
|
32
|
+
):
|
|
33
|
+
"""
|
|
34
|
+
Initialize a Validator with a connection over TCP or WS (WSS).
|
|
35
|
+
If connection_string is set, infer connection_mode, server_host, and server_port from it.
|
|
36
|
+
- connection_string: A URI string like "tcp://localhost:1234" or "ws://localhost:1234".
|
|
37
|
+
If connection_string is not set, use the provided connection_mode, server_host, and server_port.
|
|
38
|
+
TLS settings are only applicable for WSS connections or if tls=True is set.
|
|
39
|
+
- connection_mode: The mode of connection (TCP, WS, WSS).
|
|
40
|
+
- server_host: The hostname of the server to connect to.
|
|
41
|
+
- server_port: The port number of the server to connect to.
|
|
42
|
+
- tls: Whether to use TLS for the connection
|
|
43
|
+
- tls_ca_file: Path to a CA certificate file for TLS verification (optional).
|
|
44
|
+
- tls_insecure_skip_verify: Whether to skip TLS certificate verification (optional).
|
|
45
|
+
|
|
46
|
+
Raises:
|
|
47
|
+
- ValueError: If required parameters are missing or if there are conflicting parameters.
|
|
48
|
+
- TypeError: If server_port is not an integer.
|
|
49
|
+
- ConnectionError: If the connection to the server fails.
|
|
50
|
+
- ImportError: If websockets package is required but not installed for WS connections.
|
|
51
|
+
"""
|
|
52
|
+
if connection_string and (server_host or server_port):
|
|
53
|
+
raise ValueError(
|
|
54
|
+
"Cannot specify both connection_string and server_host/server_port"
|
|
55
|
+
)
|
|
56
|
+
if not connection_string and (not server_host or not server_port):
|
|
57
|
+
raise ValueError(
|
|
58
|
+
"Must specify either connection_string or both server_host and server_port"
|
|
59
|
+
)
|
|
60
|
+
if not connection_string and connection_mode == ConnectionMode.WSS and not tls:
|
|
61
|
+
raise ValueError("TLS must be enabled for WSS connections")
|
|
62
|
+
|
|
63
|
+
if not connection_string and connection_mode not in (
|
|
64
|
+
ConnectionMode.TCP,
|
|
65
|
+
ConnectionMode.WS,
|
|
66
|
+
ConnectionMode.WSS,
|
|
67
|
+
):
|
|
68
|
+
raise ValueError(f"Unsupported connection mode: {connection_mode}")
|
|
69
|
+
|
|
70
|
+
if connection_string:
|
|
71
|
+
parsed = urlparse(connection_string)
|
|
72
|
+
scheme = parsed.scheme.lower()
|
|
73
|
+
if scheme == ConnectionMode.TCP.value:
|
|
74
|
+
self.connection_mode = ConnectionMode.TCP
|
|
75
|
+
elif scheme in (ConnectionMode.WS.value, ConnectionMode.WSS.value):
|
|
76
|
+
# Map to proper ConnectionMode enum safely
|
|
77
|
+
self.connection_mode = (
|
|
78
|
+
ConnectionMode.WS
|
|
79
|
+
if scheme == ConnectionMode.WS.value
|
|
80
|
+
else ConnectionMode.WSS
|
|
81
|
+
)
|
|
82
|
+
tls = scheme == ConnectionMode.WSS.value
|
|
83
|
+
else:
|
|
84
|
+
raise ValueError(f"Unsupported scheme in connection string: {scheme}")
|
|
85
|
+
self.server_host = parsed.hostname if parsed.hostname is not None else ""
|
|
86
|
+
self.server_port = parsed.port if parsed.port is not None else 0
|
|
87
|
+
else:
|
|
88
|
+
self.connection_mode = connection_mode
|
|
89
|
+
self.server_host = server_host if server_host is not None else ""
|
|
90
|
+
self.server_port = server_port if server_port is not None else 0
|
|
91
|
+
|
|
92
|
+
if tls and not tls_ca_file and not tls_insecure_skip_verify:
|
|
93
|
+
raise ValueError(
|
|
94
|
+
"TLS is enabled but no CA file provided and insecure skip verify is not set"
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
if not tls and (tls_ca_file or tls_insecure_skip_verify):
|
|
98
|
+
raise ValueError(
|
|
99
|
+
"tls_ca_file and tls_insecure_skip_verify require tls=True"
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
if self.server_port is not None and not isinstance(self.server_port, int):
|
|
103
|
+
raise TypeError("server_port must be an integer")
|
|
104
|
+
|
|
105
|
+
self.tls = tls
|
|
106
|
+
self.tls_ca_file = tls_ca_file
|
|
107
|
+
self.tls_insecure_skip_verify = tls_insecure_skip_verify
|
|
108
|
+
self.id_counter = 0
|
|
109
|
+
|
|
110
|
+
if self.connection_mode == ConnectionMode.WSS and not self.tls:
|
|
111
|
+
raise ValueError("TLS must be enabled for WSS connections")
|
|
112
|
+
|
|
113
|
+
# Initialize connection states
|
|
114
|
+
self._ws_connection = None
|
|
115
|
+
self._ws_context = None
|
|
116
|
+
|
|
117
|
+
if self.connection_mode == ConnectionMode.TCP:
|
|
118
|
+
self._connection = self._create_tcp_connection()
|
|
119
|
+
elif self.connection_mode in (ConnectionMode.WS, ConnectionMode.WSS):
|
|
120
|
+
self._ws_context = self._create_ws_context()
|
|
121
|
+
else:
|
|
122
|
+
raise ValueError(f"Unsupported connection mode: {self.connection_mode}")
|
|
123
|
+
|
|
124
|
+
def _create_tcp_connection(self):
|
|
125
|
+
"""
|
|
126
|
+
Creates a TCP connection to the server.
|
|
127
|
+
- Returns: A socket object representing the TCP connection.
|
|
128
|
+
- Raises: ConnectionError if the connection fails.
|
|
129
|
+
- Note: If TLS is enabled, the socket will be wrapped in an SSL context.
|
|
130
|
+
"""
|
|
131
|
+
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
132
|
+
|
|
133
|
+
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
|
134
|
+
|
|
135
|
+
if self.tls:
|
|
136
|
+
context = ssl.create_default_context()
|
|
137
|
+
if self.tls_ca_file:
|
|
138
|
+
context.load_verify_locations(self.tls_ca_file)
|
|
139
|
+
if self.tls_insecure_skip_verify:
|
|
140
|
+
context.check_hostname = False
|
|
141
|
+
context.verify_mode = ssl.CERT_NONE
|
|
142
|
+
try:
|
|
143
|
+
wrapped_socket = context.wrap_socket(
|
|
144
|
+
s, server_hostname=self.server_host
|
|
145
|
+
)
|
|
146
|
+
wrapped_socket.connect((self.server_host, self.server_port))
|
|
147
|
+
except Exception as e:
|
|
148
|
+
s.close()
|
|
149
|
+
raise ConnectionError(f"Failed to connect via TLS over TCP: {e}")
|
|
150
|
+
return wrapped_socket
|
|
151
|
+
else:
|
|
152
|
+
try:
|
|
153
|
+
print(
|
|
154
|
+
f"Attempting to connect to {self.server_host}:{self.server_port} via TCP"
|
|
155
|
+
)
|
|
156
|
+
s.connect((self.server_host, self.server_port))
|
|
157
|
+
except Exception as e:
|
|
158
|
+
s.close()
|
|
159
|
+
raise ConnectionError(f"Failed to connect via TCP: {e}")
|
|
160
|
+
return s
|
|
161
|
+
|
|
162
|
+
def _create_ws_context(self):
|
|
163
|
+
"""
|
|
164
|
+
Creates a WebSocket context for WS or WSS connections.
|
|
165
|
+
- Returns: A WebSocket connection object.
|
|
166
|
+
- Raises: ImportError if the websockets package is not installed.
|
|
167
|
+
"""
|
|
168
|
+
if websockets is None:
|
|
169
|
+
raise ImportError(
|
|
170
|
+
"websockets package is required for WS connections. Please install it."
|
|
171
|
+
)
|
|
172
|
+
scheme = (
|
|
173
|
+
"wss" if (self.tls or self.connection_mode == ConnectionMode.WSS) else "ws"
|
|
174
|
+
)
|
|
175
|
+
uri = f"{scheme}://{self.server_host}:{self.server_port}"
|
|
176
|
+
ssl_context = None
|
|
177
|
+
if self.tls or self.connection_mode == ConnectionMode.WSS:
|
|
178
|
+
ssl_context = ssl.create_default_context()
|
|
179
|
+
if self.tls_ca_file:
|
|
180
|
+
ssl_context.load_verify_locations(self.tls_ca_file)
|
|
181
|
+
if self.tls_insecure_skip_verify:
|
|
182
|
+
ssl_context.check_hostname = False
|
|
183
|
+
ssl_context.verify_mode = ssl.CERT_NONE
|
|
184
|
+
return websockets.connect(uri, ssl=ssl_context)
|
|
185
|
+
|
|
186
|
+
def _generate_request_id(self):
|
|
187
|
+
"""
|
|
188
|
+
Generates a unique request ID for JSON-RPC requests.
|
|
189
|
+
- Returns: An integer representing the unique request ID.
|
|
190
|
+
"""
|
|
191
|
+
self.id_counter += 1
|
|
192
|
+
return self.id_counter
|
|
193
|
+
|
|
194
|
+
@staticmethod
|
|
195
|
+
def _validate_version(version: str) -> bool:
|
|
196
|
+
"""
|
|
197
|
+
Validates the database version string.
|
|
198
|
+
- version: The version string to validate.
|
|
199
|
+
- Returns: True if the version is valid, False otherwise.
|
|
200
|
+
- Valid formats: empty string, "default", or "major.minor.build" (e.g., "1.2.3").
|
|
201
|
+
"""
|
|
202
|
+
if not version or version == "" or version.lower() == "default":
|
|
203
|
+
return True
|
|
204
|
+
# Pattern: <majorVersion>.<minorVersion>.<buildNumber>, e.g., 1.2.3
|
|
205
|
+
pattern = r"^\d+\.\d+\.\d+$"
|
|
206
|
+
return bool(re.match(pattern, version))
|
|
207
|
+
|
|
208
|
+
def validate(
|
|
209
|
+
self,
|
|
210
|
+
query: str,
|
|
211
|
+
version: str = "",
|
|
212
|
+
) -> ValidationResult:
|
|
213
|
+
"""
|
|
214
|
+
Sends a JSON-RPC request to validate the SQL query.
|
|
215
|
+
- query: The SQL query string to validate.
|
|
216
|
+
- version: The database version string (optional).
|
|
217
|
+
- Returns: A ValidationResult object containing the validation result.
|
|
218
|
+
Raises:
|
|
219
|
+
- ValueError: If the version string is invalid or if the response ID does not match the request ID.
|
|
220
|
+
- ConnectionError: If there is an issue with sending the request or receiving the response.
|
|
221
|
+
- ImportError: If the websockets package is required but not installed for WS connections.
|
|
222
|
+
- ValueError: If the connection mode is unsupported.
|
|
223
|
+
- ValueError: If the response does not contain a valid JSON-RPC result.
|
|
224
|
+
"""
|
|
225
|
+
if not self._validate_version(version):
|
|
226
|
+
raise ValueError(
|
|
227
|
+
"Invalid version format. Expected 'major.minor.build' or empty/default."
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
request = {
|
|
231
|
+
"jsonrpc": "2.0",
|
|
232
|
+
"id": self._generate_request_id(),
|
|
233
|
+
"method": "queryChecker/validateQuery",
|
|
234
|
+
"params": {
|
|
235
|
+
"query": query,
|
|
236
|
+
"databaseVersion": version,
|
|
237
|
+
},
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
data_str = json.dumps(request)
|
|
241
|
+
data_with_content_length = f"Content-Length: {len(data_str)}\r\n\r\n{data_str}"
|
|
242
|
+
if self.connection_mode == ConnectionMode.TCP:
|
|
243
|
+
# FIX: Double-check your server specification!
|
|
244
|
+
# If it expects \r\n or a null-byte (\x00), swap '\n' out here.
|
|
245
|
+
data_bytes = (data_with_content_length + "\n").encode("utf-8")
|
|
246
|
+
# Send the data
|
|
247
|
+
self._connection.sendall(data_bytes)
|
|
248
|
+
# FIX: If using TLS, the underlying stream writer may need an explicit flush
|
|
249
|
+
if hasattr(self._connection, "flush"):
|
|
250
|
+
try:
|
|
251
|
+
self._connection.flush()
|
|
252
|
+
except AttributeError:
|
|
253
|
+
pass
|
|
254
|
+
# Now wait for response
|
|
255
|
+
response = self._recv_all(self._connection)
|
|
256
|
+
elif self.connection_mode in (ConnectionMode.WS, ConnectionMode.WSS):
|
|
257
|
+
# WebSockets pass frames natively (newlines are not required as delimiters)
|
|
258
|
+
try:
|
|
259
|
+
loop = asyncio.get_running_loop()
|
|
260
|
+
except RuntimeError:
|
|
261
|
+
loop = asyncio.new_event_loop()
|
|
262
|
+
asyncio.set_event_loop(loop)
|
|
263
|
+
|
|
264
|
+
response = loop.run_until_complete(
|
|
265
|
+
self._ws_send_and_receive(data_with_content_length)
|
|
266
|
+
)
|
|
267
|
+
else:
|
|
268
|
+
raise ValueError("Unsupported connection mode for validate")
|
|
269
|
+
|
|
270
|
+
if response.lower().startswith("content-length:"):
|
|
271
|
+
parts = response.split("\r\n\r\n", 1)
|
|
272
|
+
if len(parts) == 2:
|
|
273
|
+
response = parts[1].lstrip()
|
|
274
|
+
resp_obj = json.loads(response)
|
|
275
|
+
if "id" not in resp_obj or resp_obj["id"] != request["id"]:
|
|
276
|
+
raise ValueError("Mismatched response ID")
|
|
277
|
+
return ValidationResult.from_json(resp_obj)
|
|
278
|
+
|
|
279
|
+
def _recv_all(self, sock):
|
|
280
|
+
"""
|
|
281
|
+
Read an LSP-style response, handling Content-Length header and reading the exact body size.
|
|
282
|
+
- sock: The socket object to read from.
|
|
283
|
+
- Returns: The full response string received from the server.
|
|
284
|
+
- Raises: ConnectionError if the socket is closed before the full response is received, or ValueError if the response does not contain a valid Content-Length header.
|
|
285
|
+
"""
|
|
286
|
+
sock.settimeout(5)
|
|
287
|
+
header = b""
|
|
288
|
+
# Read header (until \r\n\r\n)
|
|
289
|
+
while b"\r\n\r\n" not in header:
|
|
290
|
+
chunk = sock.recv(1)
|
|
291
|
+
if not chunk:
|
|
292
|
+
raise ConnectionError("Socket closed before header received")
|
|
293
|
+
header += chunk
|
|
294
|
+
header_str = header.decode("utf-8")
|
|
295
|
+
# Parse Content-Length
|
|
296
|
+
content_length = None
|
|
297
|
+
for line in header_str.split("\r\n"):
|
|
298
|
+
if line.lower().startswith("content-length:"):
|
|
299
|
+
content_length = int(line.split(":", 1)[1].strip())
|
|
300
|
+
break
|
|
301
|
+
if content_length is None:
|
|
302
|
+
raise ValueError("No Content-Length header in response")
|
|
303
|
+
# Read body
|
|
304
|
+
body = b""
|
|
305
|
+
while len(body) < content_length:
|
|
306
|
+
chunk = sock.recv(content_length - len(body))
|
|
307
|
+
if not chunk:
|
|
308
|
+
raise ConnectionError("Socket closed before full body received")
|
|
309
|
+
body += chunk
|
|
310
|
+
return header_str + body.decode("utf-8")
|
|
311
|
+
|
|
312
|
+
async def _ws_send_and_receive(self, data_str: str) -> str:
|
|
313
|
+
"""
|
|
314
|
+
Send a message over WebSocket and wait for the response.
|
|
315
|
+
- data_str: The string data to send (should include Content-Length header if needed).
|
|
316
|
+
- Returns: The response string received from the server.
|
|
317
|
+
- Raises: ConnectionError if there is an issue with sending or receiving messages.
|
|
318
|
+
"""
|
|
319
|
+
# Establish persistent WebSocket connection on the first message run
|
|
320
|
+
if self._ws_connection is None:
|
|
321
|
+
self._ws_connection = await self._ws_context
|
|
322
|
+
|
|
323
|
+
await self._ws_connection.send(data_str)
|
|
324
|
+
response = await self._ws_connection.recv()
|
|
325
|
+
|
|
326
|
+
# If response comes back as bytes, decode it
|
|
327
|
+
if isinstance(response, bytes):
|
|
328
|
+
return response.decode("utf-8")
|
|
329
|
+
return response
|