sqlglot-pinot 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.
@@ -0,0 +1,73 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ lint:
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ - uses: actions/setup-python@v5
17
+ with:
18
+ python-version: "3.12"
19
+ - run: pip install ruff
20
+ - run: ruff check .
21
+ - run: ruff format --check .
22
+
23
+ unit:
24
+ runs-on: ubuntu-latest
25
+ strategy:
26
+ fail-fast: false
27
+ matrix:
28
+ python-version: ["3.10", "3.11", "3.12", "3.13"]
29
+ steps:
30
+ - uses: actions/checkout@v4
31
+ - uses: actions/setup-python@v5
32
+ with:
33
+ python-version: ${{ matrix.python-version }}
34
+ - run: pip install -e ".[dev]"
35
+ - run: pytest -m "not live"
36
+
37
+ live:
38
+ runs-on: ubuntu-latest
39
+ strategy:
40
+ fail-fast: false
41
+ matrix:
42
+ pinot: ["1.4.0", "1.5.1", "1.6.0"]
43
+ steps:
44
+ - uses: actions/checkout@v4
45
+ - uses: actions/setup-python@v5
46
+ with:
47
+ python-version: "3.12"
48
+ - run: pip install -e ".[dev]"
49
+ - name: Start Pinot QuickStart
50
+ run: |
51
+ docker run -d --name pinot -p 8000:8000 -p 9000:9000 \
52
+ -e JAVA_OPTS="-Xms1G -Xmx2G" \
53
+ apachepinot/pinot:${{ matrix.pinot }} QuickStart -type batch
54
+ - name: Wait for the sample tables
55
+ # The QuickStart loads its tables one after another; wait for every
56
+ # table the corpus queries, not just the first.
57
+ run: |
58
+ ready() {
59
+ curl -sf -X POST http://127.0.0.1:8000/query/sql \
60
+ -H 'Content-Type: application/json' \
61
+ -d "{\"sql\":\"SELECT COUNT(*) FROM $1\"}" | grep -q '"rows":\[\[[1-9]'
62
+ }
63
+ for i in $(seq 1 120); do
64
+ if ready baseballStats && ready airlineStats && ready githubEvents && ready dimBaseballTeams; then
65
+ exit 0
66
+ fi
67
+ sleep 5
68
+ done
69
+ docker logs pinot | tail -50
70
+ exit 1
71
+ - run: pytest tests/test_live.py
72
+ env:
73
+ PINOT_BROKER_URL: http://127.0.0.1:8000
@@ -0,0 +1,61 @@
1
+ name: Release
2
+
3
+ # Publishes to PyPI when a version tag such as v0.1.0 is pushed. PyPI trusts
4
+ # this workflow through a trusted publisher, so no API token is stored.
5
+ on:
6
+ push:
7
+ tags: ["v*"]
8
+
9
+ permissions:
10
+ contents: read
11
+
12
+ jobs:
13
+ build:
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - uses: actions/setup-python@v5
18
+ with:
19
+ python-version: "3.12"
20
+ - name: Check the tag matches the package version
21
+ run: |
22
+ version=$(python -c "import tomllib; print(tomllib.load(open('pyproject.toml', 'rb'))['project']['version'])")
23
+ if [ "v${version}" != "${GITHUB_REF_NAME}" ]; then
24
+ echo "Tag ${GITHUB_REF_NAME} does not match pyproject.toml version ${version}"
25
+ exit 1
26
+ fi
27
+ - run: pip install build
28
+ - run: python -m build
29
+ - uses: actions/upload-artifact@v4
30
+ with:
31
+ name: dist
32
+ path: dist/
33
+
34
+ publish:
35
+ needs: build
36
+ runs-on: ubuntu-latest
37
+ environment:
38
+ name: pypi
39
+ url: https://pypi.org/project/sqlglot-pinot/
40
+ permissions:
41
+ id-token: write
42
+ steps:
43
+ - uses: actions/download-artifact@v4
44
+ with:
45
+ name: dist
46
+ path: dist/
47
+ - uses: pypa/gh-action-pypi-publish@release/v1
48
+
49
+ github-release:
50
+ needs: publish
51
+ runs-on: ubuntu-latest
52
+ permissions:
53
+ contents: write
54
+ steps:
55
+ - uses: actions/download-artifact@v4
56
+ with:
57
+ name: dist
58
+ path: dist/
59
+ - run: gh release create "$GITHUB_REF_NAME" dist/* --repo "$GITHUB_REPOSITORY" --title "$GITHUB_REF_NAME" --generate-notes
60
+ env:
61
+ GH_TOKEN: ${{ github.token }}
@@ -0,0 +1,7 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ dist/
5
+ build/
6
+ .pytest_cache/
7
+ .ruff_cache/
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,119 @@
1
+ Metadata-Version: 2.5
2
+ Name: sqlglot-pinot
3
+ Version: 0.1.0
4
+ Summary: An Apache Pinot dialect for sqlglot
5
+ Project-URL: Homepage, https://github.com/hashroute3/sqlglot-pinot
6
+ Project-URL: Issues, https://github.com/hashroute3/sqlglot-pinot/issues
7
+ Author-email: Mahendran Vasagam <mahendran.vasagam@gmail.com>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: apache-pinot,dialect,pinot,sql,sqlglot,transpiler
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: SQL
16
+ Classifier: Topic :: Database
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: sqlglot>=30.0
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest>=8; extra == 'dev'
21
+ Requires-Dist: ruff>=0.6; extra == 'dev'
22
+ Description-Content-Type: text/markdown
23
+
24
+ # sqlglot-pinot
25
+
26
+ An [Apache Pinot](https://pinot.apache.org/) dialect for
27
+ [sqlglot](https://github.com/tobymao/sqlglot), packaged as a
28
+ [sqlglot dialect plugin](https://github.com/tobymao/sqlglot#creating-a-dialect-plugin).
29
+
30
+ With it, sqlglot can turn SQL written for another engine into SQL Pinot runs,
31
+ turn Pinot SQL into SQL for other engines, and parse and regenerate Pinot SQL
32
+ without breaking it.
33
+
34
+ ```python
35
+ import sqlglot
36
+
37
+ sqlglot.transpile("SELECT STDDEV(x), APPROX_DISTINCT(y) FROM t", read="trino", write="pinot")
38
+ # ['SELECT STDDEV_SAMP(x), DISTINCTCOUNTHLL(y) FROM t']
39
+
40
+ sqlglot.transpile(
41
+ "SELECT DATEDIFF('DAY', a, b), PERCENTILETDIGEST(x, 90) FROM t", read="pinot", write="bigquery"
42
+ )
43
+ # ['SELECT DATE_DIFF(b, a, DAY), APPROX_QUANTILES(x, 10)[9] FROM t']
44
+ ```
45
+
46
+ ## Install
47
+
48
+ ```bash
49
+ pip install sqlglot-pinot
50
+ ```
51
+
52
+ Installing the package registers the dialect with sqlglot under the name
53
+ `pinot`; there is nothing to import. You can also use the class directly:
54
+
55
+ ```python
56
+ from sqlglot_pinot import Pinot
57
+ ```
58
+
59
+ Requires Python 3.10+ and sqlglot 30 or later.
60
+
61
+ ## What it handles
62
+
63
+ The dialect builds on sqlglot's Trino dialect. Pinot's multi-stage engine is
64
+ based on Apache Calcite and shares Trino's quoting rules and most of its SQL, so
65
+ only the differences are overridden.
66
+
67
+ | SQL from other dialects | Pinot SQL generated |
68
+ |---|---|
69
+ | `STDDEV(x)`, `VARIANCE(x)` | `STDDEV_SAMP(x)`, `VAR_SAMP(x)` |
70
+ | `APPROX_DISTINCT(x)`, `APPROX_COUNT_DISTINCT(x)` | `DISTINCTCOUNTHLL(x)` |
71
+ | `APPROX_PERCENTILE(x, 0.9)` | `PERCENTILETDIGEST(x, 90)` |
72
+ | `CURRENT_TIMESTAMP` | `NOW()` |
73
+ | `DATE_DIFF('day', a, b)`, `DATEDIFF(b, a)` | `DATEDIFF('DAY', a, b)` |
74
+ | `CAST(x AS VARCHAR(10))`, `BIGINT`, `DECIMAL(10, 2)` | `CAST(x AS STRING)`, `LONG`, `BIG_DECIMAL` |
75
+ | `TIMESTAMP WITH TIME ZONE` | `TIMESTAMP` (Pinot stores UTC milliseconds) |
76
+ | `` `col` `` (MySQL) | `"col"` |
77
+ | `j ->> 'a'` | `JSON_EXTRACT_SCALAR(j, '$.a', 'STRING')` |
78
+
79
+ When it parses Pinot SQL, it keeps Pinot's own forms:
80
+ - `DATEDIFF(unit, start, end)` keeps all three arguments.
81
+ - `JSON_EXTRACT_SCALAR(json, path, type, default)` keeps its type and default.
82
+ - Function names keep the case they were written in, such as `ToDateTime` and `ago`.
83
+ - Pinot's types (`LONG`, `STRING`, `BIG_DECIMAL`, `BYTES`) and `LIMIT n OFFSET m` are unchanged.
84
+
85
+ ## How it is tested
86
+
87
+ [`tests/corpus.py`](tests/corpus.py) is a set of queries against the tables in
88
+ Pinot's batch QuickStart. It has 50 Pinot queries that have to round-trip
89
+ unchanged, and 29 queries from Postgres, Trino, MySQL, BigQuery, DuckDB and
90
+ Snowflake that have to become SQL Pinot accepts.
91
+
92
+ The unit tests check the generated SQL text. The live tests send every query to
93
+ a real Pinot broker, and CI runs them against Pinot 1.4.0, 1.5.1 and 1.6.0. All
94
+ 79 pass on each of those releases with the multi-stage engine.
95
+ `scripts/check_versions.sh 1.6.0 1.5.1` runs the same check against fresh
96
+ QuickStart containers on both engines.
97
+
98
+ Run them yourself:
99
+
100
+ ```bash
101
+ docker run -p 8000:8000 -p 9000:9000 apachepinot/pinot:1.6.0 QuickStart -type batch
102
+ PINOT_BROKER_URL=http://127.0.0.1:8000 pytest
103
+ ```
104
+
105
+ ## Limitations
106
+
107
+ - **The target is the multi-stage engine.** Pinot's single-stage engine has no
108
+ joins, CTEs, window functions, `||`, interval arithmetic or `CAST(... AS
109
+ DATE)`, so queries that use them fail there whatever dialect wrote them. The
110
+ rest of the corpus (73 of 79) also passes on the single-stage engine.
111
+ - **Percentiles are approximate.** `APPROX_PERCENTILE` maps to Pinot's
112
+ t-digest estimate. Exact `PERCENTILE_CONT` is not translated.
113
+ - **Pinot-only functions pass through as written.** Functions such as
114
+ `ToDateTime`, `JSON_MATCH` or `ago` survive a Pinot round trip but are not
115
+ rewritten for other dialects.
116
+
117
+ ## License
118
+
119
+ Apache License 2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,96 @@
1
+ # sqlglot-pinot
2
+
3
+ An [Apache Pinot](https://pinot.apache.org/) dialect for
4
+ [sqlglot](https://github.com/tobymao/sqlglot), packaged as a
5
+ [sqlglot dialect plugin](https://github.com/tobymao/sqlglot#creating-a-dialect-plugin).
6
+
7
+ With it, sqlglot can turn SQL written for another engine into SQL Pinot runs,
8
+ turn Pinot SQL into SQL for other engines, and parse and regenerate Pinot SQL
9
+ without breaking it.
10
+
11
+ ```python
12
+ import sqlglot
13
+
14
+ sqlglot.transpile("SELECT STDDEV(x), APPROX_DISTINCT(y) FROM t", read="trino", write="pinot")
15
+ # ['SELECT STDDEV_SAMP(x), DISTINCTCOUNTHLL(y) FROM t']
16
+
17
+ sqlglot.transpile(
18
+ "SELECT DATEDIFF('DAY', a, b), PERCENTILETDIGEST(x, 90) FROM t", read="pinot", write="bigquery"
19
+ )
20
+ # ['SELECT DATE_DIFF(b, a, DAY), APPROX_QUANTILES(x, 10)[9] FROM t']
21
+ ```
22
+
23
+ ## Install
24
+
25
+ ```bash
26
+ pip install sqlglot-pinot
27
+ ```
28
+
29
+ Installing the package registers the dialect with sqlglot under the name
30
+ `pinot`; there is nothing to import. You can also use the class directly:
31
+
32
+ ```python
33
+ from sqlglot_pinot import Pinot
34
+ ```
35
+
36
+ Requires Python 3.10+ and sqlglot 30 or later.
37
+
38
+ ## What it handles
39
+
40
+ The dialect builds on sqlglot's Trino dialect. Pinot's multi-stage engine is
41
+ based on Apache Calcite and shares Trino's quoting rules and most of its SQL, so
42
+ only the differences are overridden.
43
+
44
+ | SQL from other dialects | Pinot SQL generated |
45
+ |---|---|
46
+ | `STDDEV(x)`, `VARIANCE(x)` | `STDDEV_SAMP(x)`, `VAR_SAMP(x)` |
47
+ | `APPROX_DISTINCT(x)`, `APPROX_COUNT_DISTINCT(x)` | `DISTINCTCOUNTHLL(x)` |
48
+ | `APPROX_PERCENTILE(x, 0.9)` | `PERCENTILETDIGEST(x, 90)` |
49
+ | `CURRENT_TIMESTAMP` | `NOW()` |
50
+ | `DATE_DIFF('day', a, b)`, `DATEDIFF(b, a)` | `DATEDIFF('DAY', a, b)` |
51
+ | `CAST(x AS VARCHAR(10))`, `BIGINT`, `DECIMAL(10, 2)` | `CAST(x AS STRING)`, `LONG`, `BIG_DECIMAL` |
52
+ | `TIMESTAMP WITH TIME ZONE` | `TIMESTAMP` (Pinot stores UTC milliseconds) |
53
+ | `` `col` `` (MySQL) | `"col"` |
54
+ | `j ->> 'a'` | `JSON_EXTRACT_SCALAR(j, '$.a', 'STRING')` |
55
+
56
+ When it parses Pinot SQL, it keeps Pinot's own forms:
57
+ - `DATEDIFF(unit, start, end)` keeps all three arguments.
58
+ - `JSON_EXTRACT_SCALAR(json, path, type, default)` keeps its type and default.
59
+ - Function names keep the case they were written in, such as `ToDateTime` and `ago`.
60
+ - Pinot's types (`LONG`, `STRING`, `BIG_DECIMAL`, `BYTES`) and `LIMIT n OFFSET m` are unchanged.
61
+
62
+ ## How it is tested
63
+
64
+ [`tests/corpus.py`](tests/corpus.py) is a set of queries against the tables in
65
+ Pinot's batch QuickStart. It has 50 Pinot queries that have to round-trip
66
+ unchanged, and 29 queries from Postgres, Trino, MySQL, BigQuery, DuckDB and
67
+ Snowflake that have to become SQL Pinot accepts.
68
+
69
+ The unit tests check the generated SQL text. The live tests send every query to
70
+ a real Pinot broker, and CI runs them against Pinot 1.4.0, 1.5.1 and 1.6.0. All
71
+ 79 pass on each of those releases with the multi-stage engine.
72
+ `scripts/check_versions.sh 1.6.0 1.5.1` runs the same check against fresh
73
+ QuickStart containers on both engines.
74
+
75
+ Run them yourself:
76
+
77
+ ```bash
78
+ docker run -p 8000:8000 -p 9000:9000 apachepinot/pinot:1.6.0 QuickStart -type batch
79
+ PINOT_BROKER_URL=http://127.0.0.1:8000 pytest
80
+ ```
81
+
82
+ ## Limitations
83
+
84
+ - **The target is the multi-stage engine.** Pinot's single-stage engine has no
85
+ joins, CTEs, window functions, `||`, interval arithmetic or `CAST(... AS
86
+ DATE)`, so queries that use them fail there whatever dialect wrote them. The
87
+ rest of the corpus (73 of 79) also passes on the single-stage engine.
88
+ - **Percentiles are approximate.** `APPROX_PERCENTILE` maps to Pinot's
89
+ t-digest estimate. Exact `PERCENTILE_CONT` is not translated.
90
+ - **Pinot-only functions pass through as written.** Functions such as
91
+ `ToDateTime`, `JSON_MATCH` or `ago` survive a Pinot round trip but are not
92
+ rewritten for other dialects.
93
+
94
+ ## License
95
+
96
+ Apache License 2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,51 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.24"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "sqlglot-pinot"
7
+ version = "0.1.0"
8
+ description = "An Apache Pinot dialect for sqlglot"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Mahendran Vasagam", email = "mahendran.vasagam@gmail.com" }]
13
+ requires-python = ">=3.10"
14
+ dependencies = ["sqlglot>=30.0"]
15
+ keywords = ["sqlglot", "pinot", "apache-pinot", "sql", "dialect", "transpiler"]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Intended Audience :: Developers",
19
+ "License :: OSI Approved :: Apache Software License",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: SQL",
22
+ "Topic :: Database",
23
+ ]
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/hashroute3/sqlglot-pinot"
27
+ Issues = "https://github.com/hashroute3/sqlglot-pinot/issues"
28
+
29
+ [project.entry-points."sqlglot.dialects"]
30
+ pinot = "sqlglot_pinot:Pinot"
31
+
32
+ [project.optional-dependencies]
33
+ dev = ["pytest>=8", "ruff>=0.6"]
34
+
35
+ [tool.ruff]
36
+ line-length = 100
37
+ target-version = "py310"
38
+
39
+ [tool.ruff.lint]
40
+ select = ["E", "F", "I", "W", "UP", "B"]
41
+
42
+ [tool.ruff.lint.per-file-ignores]
43
+ # The corpora are SQL statements, which read best unwrapped.
44
+ "tests/*" = ["E501"]
45
+
46
+ [tool.ruff.lint.isort]
47
+ known-first-party = ["sqlglot_pinot", "corpus"]
48
+
49
+ [tool.pytest.ini_options]
50
+ testpaths = ["tests"]
51
+ markers = ["live: needs a running Pinot QuickStart (set PINOT_BROKER_URL)"]
@@ -0,0 +1,33 @@
1
+ #!/usr/bin/env bash
2
+ # Run the live corpus against fresh Pinot QuickStart containers, one version at
3
+ # a time, on both query engines.
4
+ #
5
+ # Usage: scripts/check_versions.sh 1.6.0 1.5.1 1.4.0
6
+ set -u
7
+ cd "$(dirname "$0")/.."
8
+ PY=${PYTHON:-.venv/bin/python}
9
+ BROKER_PORT=18000
10
+
11
+ ready() {
12
+ curl -sf -X POST "http://127.0.0.1:${BROKER_PORT}/query/sql" \
13
+ -H 'Content-Type: application/json' \
14
+ -d "{\"sql\":\"SELECT COUNT(*) FROM $1\"}" | grep -q '"rows":\[\[[1-9]'
15
+ }
16
+
17
+ for version in "$@"; do
18
+ name="pinot-check-${version}"
19
+ echo "=== Pinot ${version}"
20
+ docker run -d --rm --name "$name" -p "127.0.0.1:${BROKER_PORT}:8000" \
21
+ -e JAVA_OPTS="-Xms1G -Xmx2G" "apachepinot/pinot:${version}" QuickStart -type batch >/dev/null
22
+ for _ in $(seq 1 120); do
23
+ if ready baseballStats && ready airlineStats && ready githubEvents && ready dimBaseballTeams; then
24
+ break
25
+ fi
26
+ sleep 5
27
+ done
28
+ echo "--- multi-stage"
29
+ "$PY" scripts/live_check.py --broker "http://127.0.0.1:${BROKER_PORT}"
30
+ echo "--- single-stage"
31
+ "$PY" scripts/live_check.py --broker "http://127.0.0.1:${BROKER_PORT}" --single-stage | tail -1
32
+ docker stop "$name" >/dev/null
33
+ done
@@ -0,0 +1,73 @@
1
+ """Run the corpus through the dialect and against a live Pinot broker.
2
+
3
+ Usage: python scripts/live_check.py [--broker http://127.0.0.1:8000]
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import json
10
+ import sys
11
+ import urllib.request
12
+ from pathlib import Path
13
+
14
+ import sqlglot
15
+
16
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "tests"))
17
+ from corpus import CROSS, NATIVE # noqa: E402
18
+ from sqlglot_pinot import Pinot # noqa: E402
19
+
20
+ MULTISTAGE = "true"
21
+
22
+
23
+ def pinot_error(broker: str, sql: str) -> str | None:
24
+ options = f"useMultistageEngine={MULTISTAGE};timeoutMs=20000"
25
+ body = json.dumps({"sql": sql, "queryOptions": options}).encode()
26
+ req = urllib.request.Request(broker + "/query/sql", body, {"Content-Type": "application/json"})
27
+ with urllib.request.urlopen(req, timeout=30) as resp:
28
+ data = json.load(resp)
29
+ if data.get("exceptions"):
30
+ return data["exceptions"][0]["message"].splitlines()[0][:140]
31
+ return None
32
+
33
+
34
+ def main() -> int:
35
+ parser = argparse.ArgumentParser()
36
+ parser.add_argument("--broker", default="http://127.0.0.1:8000")
37
+ parser.add_argument(
38
+ "--single-stage", action="store_true", help="use Pinot's single-stage engine"
39
+ )
40
+ args = parser.parse_args()
41
+ global MULTISTAGE
42
+ MULTISTAGE = "false" if args.single_stage else "true"
43
+ failures = 0
44
+
45
+ for sql, expected in NATIVE:
46
+ before = pinot_error(args.broker, sql)
47
+ if before:
48
+ print(f"INPUT REJECTED {sql}\n !! {before}")
49
+ failures += 1
50
+ continue
51
+ out = sqlglot.transpile(sql, read=Pinot, write=Pinot)[0]
52
+ after = pinot_error(args.broker, out)
53
+ changed = out != (expected or sql)
54
+ if after or changed:
55
+ failures += 1
56
+ print(f"NATIVE {'BROKEN' if after else 'CHANGED'} {sql}\n -> {out}")
57
+ if after:
58
+ print(f" !! {after}")
59
+
60
+ for read, sql in CROSS:
61
+ out = sqlglot.transpile(sql, read=read, write=Pinot)[0]
62
+ err = pinot_error(args.broker, out)
63
+ if err:
64
+ failures += 1
65
+ print(f"CROSS[{read}] FAIL {sql}\n -> {out}\n !! {err}")
66
+
67
+ total = len(NATIVE) + len(CROSS)
68
+ print(f"\n{total - failures}/{total} passed")
69
+ return 1 if failures else 0
70
+
71
+
72
+ if __name__ == "__main__":
73
+ sys.exit(main())
@@ -0,0 +1,12 @@
1
+ """An Apache Pinot dialect for sqlglot.
2
+
3
+ Installing the package registers the dialect under the name ``pinot``::
4
+
5
+ import sqlglot
6
+ sqlglot.transpile("SELECT STDDEV(x) FROM t", read="postgres", write="pinot")
7
+ """
8
+
9
+ from sqlglot_pinot.dialect import Pinot
10
+
11
+ __all__ = ["Pinot"]
12
+ __version__ = "0.1.0"
@@ -0,0 +1,170 @@
1
+ """A sqlglot dialect for Apache Pinot."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from sqlglot import exp, generator
6
+ from sqlglot.dialects.trino import Trino
7
+ from sqlglot.helper import seq_get
8
+ from sqlglot.tokens import TokenType
9
+
10
+
11
+ def _unit_name(unit: exp.Expr | None, default: str = "DAY") -> str:
12
+ """Return a date part as Pinot writes it: an upper-case name such as DAY."""
13
+ if unit is None:
14
+ return default
15
+ return unit.name.upper() or default
16
+
17
+
18
+ def _date_diff(args: list) -> exp.Expr:
19
+ # Pinot: DATEDIFF(unit, start, end) = end - start. sqlglot's DateDiff is
20
+ # this - expression, so "this" is the end and "expression" the start.
21
+ if len(args) == 3:
22
+ return exp.DateDiff(
23
+ this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0)
24
+ )
25
+ return exp.Anonymous(this="DATEDIFF", expressions=args)
26
+
27
+
28
+ def _timestamp_diff(args: list) -> exp.Expr:
29
+ # TIMESTAMPDIFF(unit, start, end) = end - start, like DATEDIFF.
30
+ if len(args) == 3:
31
+ return exp.TimestampDiff(
32
+ this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0)
33
+ )
34
+ return exp.Anonymous(this="TIMESTAMPDIFF", expressions=args)
35
+
36
+
37
+ def _json_extract_scalar(args: list) -> exp.Expr:
38
+ # Pinot's JSON_EXTRACT_SCALAR(json, path, result_type[, default]) carries a
39
+ # result type that sqlglot's two-argument JSONExtractScalar has no place
40
+ # for, so the full call is kept as written.
41
+ if len(args) >= 3:
42
+ return exp.Anonymous(this="JSON_EXTRACT_SCALAR", expressions=args)
43
+ return exp.JSONExtractScalar(this=seq_get(args, 0), expression=seq_get(args, 1))
44
+
45
+
46
+ def _scale(value: exp.Expr, factor: float) -> exp.Expr:
47
+ """Multiply a percentile by factor, folding it when it is a literal."""
48
+ if value.is_number:
49
+ scaled = round(float(value.name) * factor, 10)
50
+ return exp.Literal.number(int(scaled) if scaled.is_integer() else scaled)
51
+ return exp.Mul(this=value.copy(), expression=exp.Literal.number(factor))
52
+
53
+
54
+ def _approx_quantile(args: list) -> exp.Expr:
55
+ # PERCENTILETDIGEST(x, 90): Pinot's percentiles are on a 0-100 scale;
56
+ # sqlglot's ApproxQuantile, like Trino's APPROX_PERCENTILE, uses 0-1.
57
+ if len(args) == 2:
58
+ return exp.ApproxQuantile(this=seq_get(args, 0), quantile=_scale(args[1], 0.01))
59
+ return exp.Anonymous(this="PERCENTILETDIGEST", expressions=args)
60
+
61
+
62
+ def _percentile(self: generator.Generator, expression: exp.ApproxQuantile) -> str:
63
+ return self.func("PERCENTILETDIGEST", expression.this, _scale(expression.args["quantile"], 100))
64
+
65
+
66
+ class Pinot(Trino):
67
+ """Apache Pinot's SQL, as accepted by its multi-stage (Calcite) engine.
68
+
69
+ Pinot quotes identifiers with double quotes and strings with single quotes,
70
+ like Trino, and accepts most of the SQL Trino's generator writes. This
71
+ dialect starts from Trino and changes what Pinot spells differently, so that
72
+ Pinot SQL round-trips unchanged and SQL from other dialects runs on Pinot.
73
+ """
74
+
75
+ # Pinot's function names are case-insensitive, and its documentation uses
76
+ # camelCase (ToDateTime, ago). Keep names as the query wrote them.
77
+ NORMALIZE_FUNCTIONS: bool | str = False
78
+
79
+ class Tokenizer(Trino.Tokenizer):
80
+ KEYWORDS = {
81
+ **Trino.Tokenizer.KEYWORDS,
82
+ "BIG_DECIMAL": TokenType.BIGDECIMAL,
83
+ "BYTES": TokenType.VARBINARY,
84
+ "LONG": TokenType.BIGINT,
85
+ "STRING": TokenType.TEXT,
86
+ }
87
+
88
+ class Parser(Trino.Parser):
89
+ FUNCTIONS = {
90
+ **Trino.Parser.FUNCTIONS,
91
+ "DATEDIFF": _date_diff,
92
+ "TIMESTAMPDIFF": _timestamp_diff,
93
+ "JSON_EXTRACT_SCALAR": _json_extract_scalar,
94
+ "NOW": lambda args: exp.CurrentTimestamp(),
95
+ "DISTINCTCOUNTHLL": lambda args: (
96
+ exp.ApproxDistinct(this=seq_get(args, 0))
97
+ if len(args) == 1
98
+ else exp.Anonymous(this="DISTINCTCOUNTHLL", expressions=args)
99
+ ),
100
+ "PERCENTILETDIGEST": _approx_quantile,
101
+ "STARTSWITH": lambda args: exp.StartsWith(
102
+ this=seq_get(args, 0), expression=seq_get(args, 1)
103
+ ),
104
+ }
105
+
106
+ class Generator(Trino.Generator):
107
+ TYPE_MAPPING = {
108
+ **Trino.Generator.TYPE_MAPPING,
109
+ exp.DataType.Type.BIGINT: "LONG",
110
+ exp.DataType.Type.BIGDECIMAL: "BIG_DECIMAL",
111
+ exp.DataType.Type.DECIMAL: "BIG_DECIMAL",
112
+ exp.DataType.Type.CHAR: "STRING",
113
+ exp.DataType.Type.NCHAR: "STRING",
114
+ exp.DataType.Type.NVARCHAR: "STRING",
115
+ exp.DataType.Type.TEXT: "STRING",
116
+ exp.DataType.Type.VARCHAR: "STRING",
117
+ exp.DataType.Type.BINARY: "BYTES",
118
+ exp.DataType.Type.VARBINARY: "BYTES",
119
+ exp.DataType.Type.TIMESTAMPTZ: "TIMESTAMP",
120
+ exp.DataType.Type.TIMESTAMPLTZ: "TIMESTAMP",
121
+ }
122
+
123
+ TRANSFORMS = {
124
+ **Trino.Generator.TRANSFORMS,
125
+ exp.ApproxDistinct: lambda self, e: self.func("DISTINCTCOUNTHLL", e.this),
126
+ exp.ApproxQuantile: _percentile,
127
+ exp.CurrentTimestamp: lambda self, e: "NOW()",
128
+ exp.DateDiff: lambda self, e: self.func(
129
+ "DATEDIFF", exp.Literal.string(_unit_name(e.unit)), e.expression, e.this
130
+ ),
131
+ exp.TimestampDiff: lambda self, e: self.func(
132
+ "TIMESTAMPDIFF", exp.var(_unit_name(e.unit)), e.expression, e.this
133
+ ),
134
+ exp.JSONExtractScalar: lambda self, e: self.func(
135
+ "JSON_EXTRACT_SCALAR", e.this, e.expression, exp.Literal.string("STRING")
136
+ ),
137
+ exp.StartsWith: lambda self, e: self.func("STARTSWITH", e.this, e.expression),
138
+ exp.Stddev: lambda self, e: self.func("STDDEV_SAMP", e.this),
139
+ exp.StddevSamp: lambda self, e: self.func("STDDEV_SAMP", e.this),
140
+ exp.StddevPop: lambda self, e: self.func("STDDEV_POP", e.this),
141
+ exp.Variance: lambda self, e: self.func("VAR_SAMP", e.this),
142
+ exp.VariancePop: lambda self, e: self.func("VAR_POP", e.this),
143
+ }
144
+
145
+ def datatype_sql(self, expression: exp.DataType) -> str:
146
+ # Pinot has one TIMESTAMP type, stored as UTC milliseconds, so a
147
+ # time-zone-aware timestamp maps to it.
148
+ if expression.this in (
149
+ exp.DataType.Type.TIMESTAMPTZ,
150
+ exp.DataType.Type.TIMESTAMPLTZ,
151
+ ):
152
+ return "TIMESTAMP"
153
+ # Pinot's types take no parameters: VARCHAR(10) is just STRING.
154
+ if expression.this in (
155
+ exp.DataType.Type.CHAR,
156
+ exp.DataType.Type.NCHAR,
157
+ exp.DataType.Type.NVARCHAR,
158
+ exp.DataType.Type.TEXT,
159
+ exp.DataType.Type.VARCHAR,
160
+ exp.DataType.Type.DECIMAL,
161
+ exp.DataType.Type.BIGDECIMAL,
162
+ ):
163
+ return self.TYPE_MAPPING[expression.this]
164
+ return super().datatype_sql(expression)
165
+
166
+ def offset_limit_modifiers(
167
+ self, expression: exp.Expr, fetch: bool, limit: exp.Fetch | exp.Limit | None
168
+ ) -> list[str]:
169
+ # Trino writes OFFSET before LIMIT; Pinot's docs write LIMIT n OFFSET m.
170
+ return generator.Generator.offset_limit_modifiers(self, expression, fetch, limit)
@@ -0,0 +1,4 @@
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ sys.path.insert(0, str(Path(__file__).parent))
@@ -0,0 +1,125 @@
1
+ """Query corpus shared by the unit and live tests.
2
+
3
+ Every query here runs on the tables loaded by Pinot's batch QuickStart
4
+ (``baseballStats``, ``airlineStats``, ``githubEvents``, ``dimBaseballTeams``),
5
+ so the live tests can check that Pinot accepts each one.
6
+ """
7
+
8
+ B = "baseballStats"
9
+ A = "airlineStats"
10
+ G = "githubEvents"
11
+ TS = "CAST('2014-01-01 00:00:00' AS TIMESTAMP)"
12
+ TS2 = "CAST('2014-01-05 00:00:00' AS TIMESTAMP)"
13
+
14
+ # Pinot SQL that must survive parsing and generating with the Pinot dialect.
15
+ # Each entry is (sql, expected output); an expected value of None means the
16
+ # output must equal the input.
17
+ NATIVE = [
18
+ # Identifiers, literals, casts and Pinot's own type names
19
+ (f'SELECT "teamID", "playerName" FROM {B} LIMIT 5', None),
20
+ (f'SELECT CAST("homeRuns" AS LONG) FROM {B} LIMIT 1', None),
21
+ (f'SELECT CAST("homeRuns" AS STRING) FROM {B} LIMIT 1', None),
22
+ (f'SELECT CAST("homeRuns" AS BIG_DECIMAL) FROM {B} LIMIT 1', None),
23
+ (f'SELECT CAST("homeRuns" AS DOUBLE) FROM {B} LIMIT 1', None),
24
+ (f"SELECT {TS} FROM {B} LIMIT 1", None),
25
+ # Aggregations, including Pinot-specific ones
26
+ (f'SELECT COUNT(*), SUM("homeRuns"), AVG("homeRuns") FROM {B}', None),
27
+ (f'SELECT DISTINCTCOUNT("teamID") FROM {B}', None),
28
+ (f'SELECT DISTINCTCOUNTHLL("teamID") FROM {B}', None),
29
+ (f'SELECT PERCENTILE("homeRuns", 90) FROM {B}', None),
30
+ (f'SELECT PERCENTILETDIGEST("homeRuns", 90) FROM {B}', None),
31
+ (f'SELECT STDDEV_SAMP("homeRuns"), STDDEV_POP("homeRuns") FROM {B}', None),
32
+ (f'SELECT VAR_SAMP("homeRuns"), VAR_POP("homeRuns") FROM {B}', None),
33
+ (f'SELECT MODE("homeRuns") FROM {B}', None),
34
+ (f'SELECT MINMAXRANGE("homeRuns") FROM {B}', None),
35
+ (f'SELECT COUNT(*) FILTER(WHERE "homeRuns" > 10) FROM {B}', None),
36
+ # Dates and times
37
+ (f"SELECT NOW() FROM {B} LIMIT 1", None),
38
+ (f"SELECT ago('P1D') FROM {B} LIMIT 1", None),
39
+ (f"SELECT DATETRUNC('DAY', \"ts\") FROM {A} LIMIT 1", None),
40
+ (f"SELECT DATE_TRUNC('DAY', \"ts\") FROM {A} LIMIT 1", None),
41
+ (f"SELECT DATEDIFF('DAY', {TS}, {TS2}) FROM {B} LIMIT 1", None),
42
+ (f"SELECT DATEDIFF('HOUR', {TS}, {TS2}) FROM {B} LIMIT 1", None),
43
+ (f"SELECT TIMESTAMPDIFF(DAY, {TS}, {TS2}) FROM {B} LIMIT 1", None),
44
+ (f"SELECT TIMESTAMPADD(DAY, 1, {TS}) FROM {B} LIMIT 1", None),
45
+ (f"SELECT ToDateTime(1388534400000, 'yyyy-MM-dd') FROM {B} LIMIT 1", None),
46
+ (f"SELECT FromDateTime('2014-01-01', 'yyyy-MM-dd') FROM {B} LIMIT 1", None),
47
+ (f"SELECT ToEpochSeconds(1388534400000) FROM {B} LIMIT 1", None),
48
+ (f'SELECT YEAR("ts"), MONTH("ts"), HOUR("ts") FROM {A} LIMIT 1', None),
49
+ (f'SELECT EXTRACT(YEAR FROM "ts") FROM {A} LIMIT 1', None),
50
+ (f"SELECT {TS} + INTERVAL '1' DAY FROM {B} LIMIT 1", None),
51
+ # Strings, regular expressions and JSON
52
+ (f'SELECT UPPER("teamID"), LOWER("teamID"), LENGTH("playerName") FROM {B} LIMIT 1', None),
53
+ (f'SELECT SUBSTR("playerName", 1, 3) FROM {B} LIMIT 1', None),
54
+ (f'SELECT CONCAT("teamID", \'-\', "playerName") FROM {B} LIMIT 1', None),
55
+ (f'SELECT "teamID" || \'-\' || "playerName" FROM {B} LIMIT 1', None),
56
+ (f"SELECT STRPOS(\"playerName\", 'a') FROM {B} LIMIT 1", None),
57
+ (f"SELECT STARTSWITH(\"playerName\", 'A') FROM {B} LIMIT 1", None),
58
+ (f"SELECT COUNT(*) FROM {B} WHERE REGEXP_LIKE(\"playerName\", '^A')", None),
59
+ (f"SELECT REGEXP_EXTRACT(\"playerName\", '^(\\w+)') FROM {B} LIMIT 1", None),
60
+ (f"SELECT JSON_EXTRACT_SCALAR(\"repo\", '$.name', 'STRING', 'none') FROM {G} LIMIT 1", None),
61
+ (f'SELECT COUNT(*) FROM {G} WHERE JSON_MATCH("repo", \'"$.name" IS NOT NULL\')', None),
62
+ # Multi-value columns
63
+ (f'SELECT ARRAYLENGTH("DivAirports") FROM {A} LIMIT 1', None),
64
+ (f'SELECT COUNTMV("DivAirports") FROM {A}', None),
65
+ # Query structure
66
+ (
67
+ f'WITH t AS (SELECT "teamID", SUM("homeRuns") AS hr FROM {B} GROUP BY "teamID") SELECT * FROM t ORDER BY hr DESC LIMIT 3',
68
+ None,
69
+ ),
70
+ (
71
+ f'SELECT b."teamID", COUNT(*) FROM {B} AS b LEFT JOIN dimBaseballTeams AS d ON b."teamID" = d."teamID" GROUP BY b."teamID" LIMIT 3',
72
+ None,
73
+ ),
74
+ (
75
+ f'SELECT "teamID", ROW_NUMBER() OVER (PARTITION BY "teamID" ORDER BY "homeRuns" DESC) FROM {B} LIMIT 3',
76
+ None,
77
+ ),
78
+ (f'SELECT "teamID" FROM {B} ORDER BY "teamID" LIMIT 3 OFFSET 2', None),
79
+ (f'SELECT "teamID", COUNT(*) FROM {B} GROUP BY "teamID" HAVING COUNT(*) > 4000', None),
80
+ (f"SELECT CASE WHEN \"homeRuns\" > 10 THEN 'hi' ELSE 'lo' END FROM {B} LIMIT 1", None),
81
+ (
82
+ f"SELECT COUNT(*) FROM {B} WHERE \"teamID\" IN ('CHN', 'PHI') AND NOT \"homeRuns\" BETWEEN 1 AND 5",
83
+ None,
84
+ ),
85
+ (f"SELECT COUNT(*) FROM {B} WHERE \"playerName\" LIKE 'A%'", None),
86
+ ]
87
+
88
+ # SQL written for other engines that, generated as Pinot SQL, must run on Pinot.
89
+ CROSS = [
90
+ ("postgres", f'SELECT CAST("yearID" AS VARCHAR), CAST("homeRuns" AS BIGINT) FROM {B} LIMIT 1'),
91
+ ("postgres", f"SELECT COUNT(*) FROM {B} WHERE \"playerName\" ILIKE '%john%'"),
92
+ ("postgres", f"SELECT COUNT(*) FROM {B} WHERE \"playerName\" ~ '^A'"),
93
+ (
94
+ "postgres",
95
+ f'SELECT LENGTH("playerName"), SUBSTRING("playerName", 1, 3), STRPOS("playerName", \'a\') FROM {B} LIMIT 1',
96
+ ),
97
+ ("postgres", f'SELECT STDDEV("homeRuns"), VARIANCE("homeRuns") FROM {B}'),
98
+ ("postgres", f'SELECT STDDEV_POP("homeRuns"), VAR_POP("homeRuns") FROM {B}'),
99
+ ("postgres", f"SELECT DATE_TRUNC('day', \"ts\"), COUNT(*) FROM {A} GROUP BY 1 LIMIT 2"),
100
+ ("postgres", f'SELECT EXTRACT(YEAR FROM "ts") FROM {A} LIMIT 1'),
101
+ ("postgres", f"SELECT COUNT(*) FROM {A} WHERE \"ts\" >= {TS} - INTERVAL '1 day'"),
102
+ ("postgres", f"SELECT CURRENT_TIMESTAMP FROM {B} LIMIT 1"),
103
+ ("postgres", f'SELECT CAST("ts" AS DATE) FROM {A} LIMIT 1'),
104
+ (
105
+ "postgres",
106
+ f'SELECT "teamID", "homeRuns" FROM {B} ORDER BY "homeRuns" DESC NULLS LAST LIMIT 3',
107
+ ),
108
+ ("postgres", f'SELECT COUNT(DISTINCT "teamID") FROM {B}'),
109
+ ("trino", f'SELECT APPROX_DISTINCT("teamID") FROM {B}'),
110
+ ("trino", f'SELECT APPROX_PERCENTILE("homeRuns", 0.9) FROM {B}'),
111
+ ("trino", f"SELECT DATE_DIFF('day', {TS}, {TS2}) FROM {B} LIMIT 1"),
112
+ ("trino", f"SELECT DATE_ADD('day', 1, {TS}) FROM {B} LIMIT 1"),
113
+ ("trino", f"SELECT DATE_TRUNC('month', \"ts\") FROM {A} LIMIT 1"),
114
+ ("trino", f"SELECT REGEXP_LIKE(\"playerName\", '^A') FROM {B} LIMIT 1"),
115
+ ("mysql", f"SELECT DATEDIFF({TS2}, {TS}) FROM {B} LIMIT 1"),
116
+ ("mysql", f"SELECT NOW() FROM {B} LIMIT 1"),
117
+ ("mysql", f"SELECT `teamID`, COUNT(*) FROM {B} GROUP BY `teamID` LIMIT 3"),
118
+ ("bigquery", f"SELECT DATE_DIFF({TS2}, {TS}, DAY) FROM {B} LIMIT 1"),
119
+ ("bigquery", f"SELECT APPROX_COUNT_DISTINCT(teamID) FROM {B}"),
120
+ ("bigquery", f"SELECT CURRENT_TIMESTAMP() FROM {B} LIMIT 1"),
121
+ ("duckdb", f"SELECT DATE_DIFF('day', {TS}, {TS2}) FROM {B} LIMIT 1"),
122
+ ("duckdb", f'SELECT APPROX_COUNT_DISTINCT("teamID") FROM {B}'),
123
+ ("snowflake", f"SELECT DATEDIFF(day, {TS}, {TS2}) FROM {B} LIMIT 1"),
124
+ ("snowflake", f'SELECT APPROX_COUNT_DISTINCT("teamID") FROM {B}'),
125
+ ]
@@ -0,0 +1,115 @@
1
+ """Unit tests for the Pinot dialect. They need no Pinot cluster."""
2
+
3
+ import pytest
4
+ import sqlglot
5
+
6
+ from corpus import CROSS, NATIVE
7
+ from sqlglot_pinot import Pinot
8
+
9
+
10
+ def pinot(sql: str, read: str = "pinot") -> str:
11
+ return sqlglot.transpile(sql, read=read, write="pinot")[0]
12
+
13
+
14
+ def test_registered_as_a_plugin_dialect():
15
+ """The entry point makes the dialect available by name."""
16
+ assert sqlglot.Dialect.get_or_raise("pinot").__class__ is Pinot
17
+
18
+
19
+ @pytest.mark.parametrize("sql,expected", NATIVE, ids=[s[:60] for s, _ in NATIVE])
20
+ def test_pinot_sql_round_trips(sql, expected):
21
+ assert pinot(sql) == (expected or sql)
22
+
23
+
24
+ @pytest.mark.parametrize(
25
+ "read,sql,expected",
26
+ [
27
+ # Statistics
28
+ (
29
+ "postgres",
30
+ "SELECT STDDEV(x), VARIANCE(x) FROM t",
31
+ "SELECT STDDEV_SAMP(x), VAR_SAMP(x) FROM t",
32
+ ),
33
+ (
34
+ "postgres",
35
+ "SELECT STDDEV_POP(x), VAR_POP(x) FROM t",
36
+ "SELECT STDDEV_POP(x), VAR_POP(x) FROM t",
37
+ ),
38
+ ("trino", "SELECT APPROX_DISTINCT(x) FROM t", "SELECT DISTINCTCOUNTHLL(x) FROM t"),
39
+ ("bigquery", "SELECT APPROX_COUNT_DISTINCT(x) FROM t", "SELECT DISTINCTCOUNTHLL(x) FROM t"),
40
+ (
41
+ "trino",
42
+ "SELECT APPROX_PERCENTILE(x, 0.9) FROM t",
43
+ "SELECT PERCENTILETDIGEST(x, 90) FROM t",
44
+ ),
45
+ (
46
+ "trino",
47
+ "SELECT APPROX_PERCENTILE(x, 0.995) FROM t",
48
+ "SELECT PERCENTILETDIGEST(x, 99.5) FROM t",
49
+ ),
50
+ # Dates
51
+ ("postgres", "SELECT CURRENT_TIMESTAMP", "SELECT NOW()"),
52
+ ("bigquery", "SELECT CURRENT_TIMESTAMP()", "SELECT NOW()"),
53
+ ("trino", "SELECT DATE_DIFF('day', a, b)", "SELECT DATEDIFF('DAY', a, b)"),
54
+ ("duckdb", "SELECT DATE_DIFF('hour', a, b)", "SELECT DATEDIFF('HOUR', a, b)"),
55
+ ("bigquery", "SELECT DATE_DIFF(b, a, DAY)", "SELECT DATEDIFF('DAY', a, b)"),
56
+ # Types: Pinot's names, without parameters or time zones
57
+ ("postgres", "SELECT CAST(x AS VARCHAR(10))", "SELECT CAST(x AS STRING)"),
58
+ ("postgres", "SELECT CAST(x AS BIGINT)", "SELECT CAST(x AS LONG)"),
59
+ ("postgres", "SELECT CAST(x AS DECIMAL(10, 2))", "SELECT CAST(x AS BIG_DECIMAL)"),
60
+ ("postgres", "SELECT CAST(x AS TIMESTAMPTZ)", "SELECT CAST(x AS TIMESTAMP)"),
61
+ ("postgres", "SELECT CAST(x AS BYTEA)", "SELECT CAST(x AS BYTES)"),
62
+ # Identifiers and strings
63
+ ("mysql", "SELECT `a b` FROM t", 'SELECT "a b" FROM t'),
64
+ ("postgres", "SELECT 'it''s'", "SELECT 'it''s'"),
65
+ (
66
+ "postgres",
67
+ "SELECT x FROM t WHERE y ILIKE '%a%'",
68
+ "SELECT x FROM t WHERE LOWER(y) LIKE LOWER('%a%')",
69
+ ),
70
+ ("postgres", "SELECT x FROM t LIMIT 3 OFFSET 2", "SELECT x FROM t LIMIT 3 OFFSET 2"),
71
+ # JSON: Pinot needs a result type
72
+ (
73
+ "postgres",
74
+ "SELECT j ->> 'a' FROM t",
75
+ "SELECT JSON_EXTRACT_SCALAR(j, '$.a', 'STRING') FROM t",
76
+ ),
77
+ ],
78
+ )
79
+ def test_other_dialects_to_pinot(read, sql, expected):
80
+ assert pinot(sql, read=read) == expected
81
+
82
+
83
+ @pytest.mark.parametrize(
84
+ "write,expected",
85
+ [
86
+ (
87
+ "trino",
88
+ "SELECT DATE_DIFF('DAY', a, b), APPROX_DISTINCT(x), APPROX_PERCENTILE(x, 0.9), CURRENT_TIMESTAMP",
89
+ ),
90
+ (
91
+ "bigquery",
92
+ "SELECT DATE_DIFF(b, a, DAY), APPROX_COUNT_DISTINCT(x), APPROX_QUANTILES(x, 10)[9], CURRENT_TIMESTAMP()",
93
+ ),
94
+ (
95
+ "snowflake",
96
+ "SELECT DATEDIFF(DAY, a, b), APPROX_COUNT_DISTINCT(x), APPROX_PERCENTILE(x, 0.9), CURRENT_TIMESTAMP()",
97
+ ),
98
+ ],
99
+ )
100
+ def test_pinot_to_other_dialects(write, expected):
101
+ sql = "SELECT DATEDIFF('DAY', a, b), DISTINCTCOUNTHLL(x), PERCENTILETDIGEST(x, 90), NOW()"
102
+ assert sqlglot.transpile(sql, read="pinot", write=write)[0] == expected
103
+
104
+
105
+ def test_function_names_keep_their_case():
106
+ """Pinot documents camelCase names; they pass through as written."""
107
+ assert pinot("SELECT ToDateTime(ts, 'yyyy-MM-dd'), ago('P1D')") == (
108
+ "SELECT ToDateTime(ts, 'yyyy-MM-dd'), ago('P1D')"
109
+ )
110
+
111
+
112
+ def test_cross_corpus_generates_without_errors():
113
+ """Every cross-dialect corpus query at least generates Pinot SQL."""
114
+ for read, sql in CROSS:
115
+ assert pinot(sql, read=read)
@@ -0,0 +1,48 @@
1
+ """Checks against a running Pinot QuickStart cluster.
2
+
3
+ Set PINOT_BROKER_URL (for example http://127.0.0.1:8000) to run them; they are
4
+ skipped otherwise. The cluster must have loaded the batch QuickStart tables.
5
+ """
6
+
7
+ import json
8
+ import os
9
+ import urllib.request
10
+
11
+ import pytest
12
+ import sqlglot
13
+
14
+ from corpus import CROSS, NATIVE
15
+
16
+ BROKER = os.environ.get("PINOT_BROKER_URL", "")
17
+
18
+ pytestmark = [
19
+ pytest.mark.live,
20
+ pytest.mark.skipif(not BROKER, reason="PINOT_BROKER_URL is not set"),
21
+ ]
22
+
23
+
24
+ def pinot_error(sql: str) -> str | None:
25
+ body = json.dumps(
26
+ {"sql": sql, "queryOptions": "useMultistageEngine=true;timeoutMs=20000"}
27
+ ).encode()
28
+ request = urllib.request.Request(
29
+ BROKER.rstrip("/") + "/query/sql", body, {"Content-Type": "application/json"}
30
+ )
31
+ with urllib.request.urlopen(request, timeout=30) as response:
32
+ data = json.load(response)
33
+ if data.get("exceptions"):
34
+ return data["exceptions"][0]["message"]
35
+ return None
36
+
37
+
38
+ @pytest.mark.parametrize("sql", [sql for sql, _ in NATIVE], ids=[s[:60] for s, _ in NATIVE])
39
+ def test_round_tripped_pinot_sql_still_runs(sql):
40
+ assert pinot_error(sql) is None, "the corpus query itself must run on Pinot"
41
+ out = sqlglot.transpile(sql, read="pinot", write="pinot")[0]
42
+ assert pinot_error(out) is None, out
43
+
44
+
45
+ @pytest.mark.parametrize("read,sql", CROSS, ids=[f"{r}: {s[:50]}" for r, s in CROSS])
46
+ def test_other_dialects_run_on_pinot(read, sql):
47
+ out = sqlglot.transpile(sql, read=read, write="pinot")[0]
48
+ assert pinot_error(out) is None, out