sqlglot-odps 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.
- sqlglot_odps-0.1.0/.github/workflows/release.yml +80 -0
- sqlglot_odps-0.1.0/.gitignore +18 -0
- sqlglot_odps-0.1.0/.python-version +1 -0
- sqlglot_odps-0.1.0/CHANGELOG.md +7 -0
- sqlglot_odps-0.1.0/LICENSE +21 -0
- sqlglot_odps-0.1.0/PKG-INFO +185 -0
- sqlglot_odps-0.1.0/README.md +165 -0
- sqlglot_odps-0.1.0/pyproject.toml +43 -0
- sqlglot_odps-0.1.0/src/sqlglot_odps/__init__.py +21 -0
- sqlglot_odps-0.1.0/src/sqlglot_odps/dialect.py +42 -0
- sqlglot_odps-0.1.0/src/sqlglot_odps/generator.py +381 -0
- sqlglot_odps-0.1.0/src/sqlglot_odps/parser.py +738 -0
- sqlglot_odps-0.1.0/src/sqlglot_odps/py.typed +0 -0
- sqlglot_odps-0.1.0/src/sqlglot_odps/statements.py +86 -0
- sqlglot_odps-0.1.0/tests/__init__.py +0 -0
- sqlglot_odps-0.1.0/tests/test_maxcompute.py +1330 -0
- sqlglot_odps-0.1.0/tests/test_statement_kind.py +90 -0
- sqlglot_odps-0.1.0/tests/test_statement_syntax.py +230 -0
- sqlglot_odps-0.1.0/uv.lock +213 -0
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
name: Test and publish
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
tags: ['v*']
|
|
7
|
+
pull_request:
|
|
8
|
+
branches: [main]
|
|
9
|
+
|
|
10
|
+
permissions:
|
|
11
|
+
contents: read
|
|
12
|
+
|
|
13
|
+
jobs:
|
|
14
|
+
test:
|
|
15
|
+
runs-on: ${{ matrix.runner }}
|
|
16
|
+
strategy:
|
|
17
|
+
fail-fast: false
|
|
18
|
+
matrix:
|
|
19
|
+
include:
|
|
20
|
+
- python: '3.9'
|
|
21
|
+
runner: ubuntu-22.04
|
|
22
|
+
- python: '3.12'
|
|
23
|
+
runner: ubuntu-latest
|
|
24
|
+
steps:
|
|
25
|
+
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
|
26
|
+
- uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
|
|
27
|
+
with:
|
|
28
|
+
python-version: ${{ matrix.python }}
|
|
29
|
+
- run: python -m pip install -e . 'sqlglot==30.1.0' pytest
|
|
30
|
+
- run: python -m pytest
|
|
31
|
+
|
|
32
|
+
build:
|
|
33
|
+
needs: test
|
|
34
|
+
runs-on: ubuntu-latest
|
|
35
|
+
steps:
|
|
36
|
+
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
|
37
|
+
- uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
|
|
38
|
+
with:
|
|
39
|
+
python-version: '3.12'
|
|
40
|
+
- name: Check release tag
|
|
41
|
+
if: github.ref_type == 'tag'
|
|
42
|
+
run: |
|
|
43
|
+
python - <<'PY'
|
|
44
|
+
import os
|
|
45
|
+
import tomllib
|
|
46
|
+
from pathlib import Path
|
|
47
|
+
|
|
48
|
+
version = tomllib.loads(Path('pyproject.toml').read_text())['project']['version']
|
|
49
|
+
if os.environ['GITHUB_REF_NAME'] != f'v{version}':
|
|
50
|
+
raise SystemExit('The tag must match the package version')
|
|
51
|
+
PY
|
|
52
|
+
- run: python -m pip install build twine
|
|
53
|
+
- run: python -m build
|
|
54
|
+
- run: python -m twine check --strict dist/*
|
|
55
|
+
- name: Test installed wheel with current SQLGlot
|
|
56
|
+
run: |
|
|
57
|
+
python -m pip install dist/*.whl pytest
|
|
58
|
+
python -m pytest tests/test_statement_kind.py tests/test_statement_syntax.py
|
|
59
|
+
- if: github.ref_type == 'tag'
|
|
60
|
+
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
|
|
61
|
+
with:
|
|
62
|
+
name: distributions
|
|
63
|
+
path: dist/
|
|
64
|
+
if-no-files-found: error
|
|
65
|
+
|
|
66
|
+
publish:
|
|
67
|
+
if: github.repository == 'dingxin-tech/sqlglot-odps' && github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
|
|
68
|
+
needs: build
|
|
69
|
+
runs-on: ubuntu-latest
|
|
70
|
+
environment:
|
|
71
|
+
name: pypi
|
|
72
|
+
url: https://pypi.org/project/sqlglot-odps/
|
|
73
|
+
permissions:
|
|
74
|
+
id-token: write
|
|
75
|
+
steps:
|
|
76
|
+
- uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7
|
|
77
|
+
with:
|
|
78
|
+
name: distributions
|
|
79
|
+
path: dist/
|
|
80
|
+
- uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
3.12
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
- Register the `odps` SQLGlot dialect for MaxCompute.
|
|
6
|
+
- Parse and generate supported MaxCompute queries, DDL, and DML, including partition writes and shared-source multi-inserts.
|
|
7
|
+
- Classify standalone statements and submitted SQL scripts. Keep ordered `SET` configuration in the script AST.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 azurechen97
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: sqlglot-odps
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: MaxCompute dialect plugin for SQLGlot
|
|
5
|
+
Project-URL: Homepage, https://github.com/dingxin-tech/sqlglot-odps
|
|
6
|
+
Project-URL: Repository, https://github.com/dingxin-tech/sqlglot-odps
|
|
7
|
+
Author: azurechen97
|
|
8
|
+
Maintainer: Dingxin
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: SQL
|
|
17
|
+
Requires-Python: >=3.9
|
|
18
|
+
Requires-Dist: sqlglot<31,>=30.1.0
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# sqlglot-odps
|
|
22
|
+
|
|
23
|
+
A [SQLGlot](https://github.com/tobymao/sqlglot) dialect plugin for [Alibaba Cloud MaxCompute](https://www.alibabacloud.com/product/maxcompute) (formerly ODPS).
|
|
24
|
+
|
|
25
|
+
Registers the `odps` dialect via Python entry points so that SQLGlot can parse and generate MaxCompute SQL.
|
|
26
|
+
|
|
27
|
+
This is an independent community project.
|
|
28
|
+
|
|
29
|
+
## Installation
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
python -m pip install sqlglot-odps
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Requires Python 3.9+ and SQLGlot 30.x starting at 30.1.0. The entry point `odps` lets this plugin coexist with the community `maxcompute` dialect.
|
|
36
|
+
|
|
37
|
+
## Usage
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
import sqlglot
|
|
41
|
+
|
|
42
|
+
# Parse MaxCompute SQL
|
|
43
|
+
ast = sqlglot.parse_one("SELECT DATEADD(dt, 1, 'DAY')", read="odps")
|
|
44
|
+
|
|
45
|
+
# Transpile from another dialect to MaxCompute
|
|
46
|
+
sqlglot.transpile("SELECT DATE_ADD(dt, 1)", read="spark", write="odps")
|
|
47
|
+
# ["SELECT DATEADD(dt, 1, 'DAY')"]
|
|
48
|
+
|
|
49
|
+
# Transpile from MaxCompute to another dialect
|
|
50
|
+
sqlglot.transpile("SELECT DATETRUNC(dt, 'MONTH')", read="odps", write="spark")
|
|
51
|
+
# ["SELECT TRUNC(dt, 'MONTH')"]
|
|
52
|
+
|
|
53
|
+
# TO_DATE return type depends on args:
|
|
54
|
+
# without format → DATE (exp.TsOrDsToDate)
|
|
55
|
+
# with format → DATETIME (exp.StrToTime)
|
|
56
|
+
sqlglot.transpile("TO_DATE('20240101', 'yyyymmdd')", read="odps", write="spark")
|
|
57
|
+
# ["TO_TIMESTAMP('20240101', 'yyyymmdd')"]
|
|
58
|
+
|
|
59
|
+
# Round-trip MaxCompute DDL
|
|
60
|
+
sqlglot.transpile(
|
|
61
|
+
"CREATE TABLE t (id BIGINT) LIFECYCLE 30",
|
|
62
|
+
read="odps",
|
|
63
|
+
write="odps",
|
|
64
|
+
)
|
|
65
|
+
# ["CREATE TABLE t (id BIGINT) LIFECYCLE 30"]
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Statement classification
|
|
69
|
+
|
|
70
|
+
`parse_script` returns one `sqlglot.exp.Block` for a submitted script and retains the statements in order. `classify_script` returns one kind for that block. `SET` statements stay in the block as configuration. A script containing only settings is `OTHER`, a script with multiple different operation kinds is `MIXED`, and any unrecognized statement makes the script `UNKNOWN`.
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
from sqlglot_odps import classify_script, parse_script
|
|
74
|
+
|
|
75
|
+
sql = """
|
|
76
|
+
SET odps.sql.type.system.odps2=true;
|
|
77
|
+
SET odps.sql.submit.mode=script;
|
|
78
|
+
SELECT 1 AS id;
|
|
79
|
+
"""
|
|
80
|
+
script = parse_script(sql)
|
|
81
|
+
print(classify_script(sql).value) # DQL
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
`classify` returns one `StatementKind` per parsed statement, in script order. For an existing SQLGlot statement or block, call `statement_kind(ast)`.
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
from sqlglot import parse_one
|
|
88
|
+
from sqlglot_odps import classify, statement_kind
|
|
89
|
+
|
|
90
|
+
sql = """
|
|
91
|
+
SET odps.sql.type.system.odps2=true;
|
|
92
|
+
CREATE TABLE staging LIFECYCLE 7 AS SELECT id FROM events;
|
|
93
|
+
WITH src AS (SELECT id FROM staging) INSERT INTO target SELECT id FROM src;
|
|
94
|
+
SELECT id FROM target;
|
|
95
|
+
"""
|
|
96
|
+
print([kind.value for kind in classify(sql)]) # ['OTHER', 'DDL', 'DML', 'DQL']
|
|
97
|
+
|
|
98
|
+
ast = parse_one("SHOW PARTITIONS target", read="odps")
|
|
99
|
+
print(statement_kind(ast).value) # DQL
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
| Kind | Examples |
|
|
103
|
+
|---|---|
|
|
104
|
+
| `DDL` | `CREATE` including CTAS, `ALTER`, `DROP`, `TRUNCATE TABLE` |
|
|
105
|
+
| `DML` | `INSERT`, `UPDATE`, `DELETE`, `MERGE`, data loading and transfer |
|
|
106
|
+
| `DQL` | Queries and set operations, supported `SHOW` variants, `DESCRIBE`, `EXPLAIN`, `READ` |
|
|
107
|
+
| `OTHER` | `SET`, `USE`, parsed `GRANT` and `REVOKE`, `ANALYZE`, native SQL variable assignments |
|
|
108
|
+
| `MIXED` | A script with multiple different operation kinds |
|
|
109
|
+
| `UNKNOWN` | Opaque or unrecognized statements, and empty scripts |
|
|
110
|
+
|
|
111
|
+
Empty statements and comments are skipped. SQLGlot parse and tokenizer errors propagate to the caller. Classification describes the outer operation. A query inside CTAS or `INSERT` supplies rows to that operation. An `EXPLAIN` that contains an `INSERT` is a DQL operation.
|
|
112
|
+
|
|
113
|
+
### Statement syntax
|
|
114
|
+
|
|
115
|
+
This checkout adds structured parsing and MaxCompute SQL generation for shared-source multi-insert, partition-targeted writes, `INSERT OVERWRITE ... IF NOT EXISTS`, auto partitioning and clustering, multi-partition alter, column-level truncate, temporary CTAS, Java function resources, and selected metadata and data-loading statements. Queries preserve `QUALIFY`, time travel, `ZORDER BY`, named struct fields, and `@` variables when rendered as MaxCompute SQL.
|
|
116
|
+
|
|
117
|
+
Coverage is partial. Compound `BEGIN ... END` scripts require a script parser, and less common administrative commands may produce `UNKNOWN` or a parse error. Compatibility tests exercise SQL syntax. Server-side feature flags, name resolution, and execution require MaxCompute. For MaxCompute-specific statement extensions, generate with `write="odps"`; migration to another engine requires checking the semantics of each clause.
|
|
118
|
+
|
|
119
|
+
## What's supported
|
|
120
|
+
|
|
121
|
+
### Parser — MaxCompute → canonical AST
|
|
122
|
+
|
|
123
|
+
| Category | Functions |
|
|
124
|
+
|---|---|
|
|
125
|
+
| Date arithmetic | `DATEADD`, `DATE_SUB`, `DATEDIFF`, `ADD_MONTHS`, `MONTHS_BETWEEN` |
|
|
126
|
+
| Date extraction | `DATEPART`, `DATETRUNC`, `TRUNC_TIME`, `DAY`, `MONTH`, `YEAR`, `HOUR`, `MINUTE`, `SECOND`, `QUARTER`, `DAYOFMONTH`, `DAYOFWEEK`, `DAYOFYEAR`, `WEEKDAY`, `WEEKOFYEAR` |
|
|
127
|
+
| Date conversion | `TO_DATE`, `DATE_FORMAT`, `TO_CHAR`, `FROM_UNIXTIME`, `FROM_UTC_TIMESTAMP`, `TO_MILLIS`, `ISDATE` |
|
|
128
|
+
| Current date/time | `GETDATE`, `NOW`, `CURRENT_TIMESTAMP`, `CURRENT_TIMEZONE` |
|
|
129
|
+
| Last/next day | `LAST_DAY`, `LASTDAY`, `NEXT_DAY` |
|
|
130
|
+
| String | `TOLOWER`, `TOUPPER`, `REGEXP_COUNT`, `SPLIT_PART`, `SUBSTR` |
|
|
131
|
+
| Aggregate | `WM_CONCAT`, `COUNT_IF`, `ARG_MAX`, `ARG_MIN`, `MAX_BY`, `MIN_BY`, `ANY_VALUE`, `APPROX_DISTINCT`, `STDDEV_SAMP`, `COVAR_POP`, `COVAR_SAMP`, `CORR`, `MEDIAN`, `PERCENTILE_APPROX`, `BITWISE_AND_AGG`, `BITWISE_OR_AGG`, `BITWISE_XOR_AGG` |
|
|
132
|
+
| Array | `ALL_MATCH`, `ANY_MATCH`, `ARRAY_SORT`, `ARRAY_DISTINCT`, `ARRAY_EXCEPT`, `ARRAY_JOIN`, `ARRAY_MAX`, `ARRAY_MIN`, `ARRAYS_OVERLAP`, `ARRAYS_ZIP`, `ARRAY_INTERSECT`, `ARRAY_POSITION`, `ARRAY_REMOVE`, `ARRAY_CONTAINS`, `SLICE` |
|
|
133
|
+
| Map | `MAP_CONCAT`, `MAP_FROM_ENTRIES` |
|
|
134
|
+
| JSON / misc | `FROM_JSON`, `GET_JSON_OBJECT`, `JSON_TUPLE`, `GET_USER_ID`, `REGEXP_SUBSTR`, `TO_MILLIS`, `ISDATE` |
|
|
135
|
+
|
|
136
|
+
Functions not listed are handled via Hive inheritance and work without explicit mapping (e.g. `SPLIT`, `REGEXP_EXTRACT`, `COLLECT_LIST`, `PERCENTILE`, all math/trig functions, window functions).
|
|
137
|
+
|
|
138
|
+
### Generator — canonical AST → MaxCompute SQL
|
|
139
|
+
|
|
140
|
+
Explicit transforms on top of Hive:
|
|
141
|
+
|
|
142
|
+
| Expression | MaxCompute output | Note |
|
|
143
|
+
|---|---|---|
|
|
144
|
+
| `DATEADD` / `DATE_SUB` | `DATEADD(dt, ±n, 'UNIT')` | Correct negation for `DATE_SUB` |
|
|
145
|
+
| `DATEDIFF` | `DATEDIFF(dt1, dt2[, unit])` | |
|
|
146
|
+
| `DATETRUNC` | `DATETRUNC(dt, 'unit')` | Week units: `'week(monday)'` etc. |
|
|
147
|
+
| `DATEPART` | `DATEPART(dt, 'UNIT')` | |
|
|
148
|
+
| `TO_DATE(str, fmt)` | `TO_DATE(str, fmt)` | Maps to `exp.StrToTime` (DATETIME) |
|
|
149
|
+
| `TO_DATE(str)` | `TO_DATE(str)` | Maps to `exp.TsOrDsToDate` (DATE) |
|
|
150
|
+
| `CurrentTimestamp` | `GETDATE()` | Covers `GETDATE`, `NOW`, `CURRENT_TIMESTAMP` |
|
|
151
|
+
| `CurrentDatetime` | `NOW()` | For BigQuery-origin `CURRENT_DATETIME` |
|
|
152
|
+
| `SPACE(n)` | `SPACE(n)` | Hive emits `REPEAT(' ', n)` |
|
|
153
|
+
| `VAR_POP(x)` | `VAR_POP(x)` | Hive emits `VARIANCE_POP` |
|
|
154
|
+
| `VAR_SAMP(x)` | `VAR_SAMP(x)` | Hive emits `VARIANCE` |
|
|
155
|
+
| `INSTR(str, sub)` | `INSTR(str, sub)` | Hive emits `LOCATE(sub, str)` |
|
|
156
|
+
| `SUBSTR(str, pos, len)` | `SUBSTR(...)` | Hive emits `SUBSTRING` |
|
|
157
|
+
| Type: `VARCHAR`/`CHAR`/`TEXT` | `STRING` | |
|
|
158
|
+
| Type: `DATETIME` | `DATETIME` | |
|
|
159
|
+
|
|
160
|
+
### DDL
|
|
161
|
+
|
|
162
|
+
- `LIFECYCLE n` — table retention in days
|
|
163
|
+
- `RANGE CLUSTERED BY (cols) [SORTED BY (cols)] INTO n BUCKETS`
|
|
164
|
+
- `AUTO PARTITIONED BY (TRUNC_TIME(col, 'unit') [AS alias])`
|
|
165
|
+
- `TBLPROPERTIES ('key'='value')` — coexists correctly with `LIFECYCLE`
|
|
166
|
+
- `COMMENT` on columns and tables
|
|
167
|
+
|
|
168
|
+
## Development
|
|
169
|
+
|
|
170
|
+
```bash
|
|
171
|
+
uv sync # install dependencies
|
|
172
|
+
uv run pytest # run all tests
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
## License
|
|
176
|
+
|
|
177
|
+
MIT
|
|
178
|
+
|
|
179
|
+
## License
|
|
180
|
+
|
|
181
|
+
MIT. This project builds on [azurechen97/sqlglot-maxcompute 0.4.0](https://github.com/azurechen97/sqlglot-maxcompute/tree/v0.4.0) and retains the original copyright notice. See [LICENSE](LICENSE).
|
|
182
|
+
|
|
183
|
+
## Contributing
|
|
184
|
+
|
|
185
|
+
Use Python 3.9 or newer. Run the regression suite with `uv run --locked pytest`. Use `python -m build` to build a wheel and source distribution.
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
# sqlglot-odps
|
|
2
|
+
|
|
3
|
+
A [SQLGlot](https://github.com/tobymao/sqlglot) dialect plugin for [Alibaba Cloud MaxCompute](https://www.alibabacloud.com/product/maxcompute) (formerly ODPS).
|
|
4
|
+
|
|
5
|
+
Registers the `odps` dialect via Python entry points so that SQLGlot can parse and generate MaxCompute SQL.
|
|
6
|
+
|
|
7
|
+
This is an independent community project.
|
|
8
|
+
|
|
9
|
+
## Installation
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
python -m pip install sqlglot-odps
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Requires Python 3.9+ and SQLGlot 30.x starting at 30.1.0. The entry point `odps` lets this plugin coexist with the community `maxcompute` dialect.
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
import sqlglot
|
|
21
|
+
|
|
22
|
+
# Parse MaxCompute SQL
|
|
23
|
+
ast = sqlglot.parse_one("SELECT DATEADD(dt, 1, 'DAY')", read="odps")
|
|
24
|
+
|
|
25
|
+
# Transpile from another dialect to MaxCompute
|
|
26
|
+
sqlglot.transpile("SELECT DATE_ADD(dt, 1)", read="spark", write="odps")
|
|
27
|
+
# ["SELECT DATEADD(dt, 1, 'DAY')"]
|
|
28
|
+
|
|
29
|
+
# Transpile from MaxCompute to another dialect
|
|
30
|
+
sqlglot.transpile("SELECT DATETRUNC(dt, 'MONTH')", read="odps", write="spark")
|
|
31
|
+
# ["SELECT TRUNC(dt, 'MONTH')"]
|
|
32
|
+
|
|
33
|
+
# TO_DATE return type depends on args:
|
|
34
|
+
# without format → DATE (exp.TsOrDsToDate)
|
|
35
|
+
# with format → DATETIME (exp.StrToTime)
|
|
36
|
+
sqlglot.transpile("TO_DATE('20240101', 'yyyymmdd')", read="odps", write="spark")
|
|
37
|
+
# ["TO_TIMESTAMP('20240101', 'yyyymmdd')"]
|
|
38
|
+
|
|
39
|
+
# Round-trip MaxCompute DDL
|
|
40
|
+
sqlglot.transpile(
|
|
41
|
+
"CREATE TABLE t (id BIGINT) LIFECYCLE 30",
|
|
42
|
+
read="odps",
|
|
43
|
+
write="odps",
|
|
44
|
+
)
|
|
45
|
+
# ["CREATE TABLE t (id BIGINT) LIFECYCLE 30"]
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Statement classification
|
|
49
|
+
|
|
50
|
+
`parse_script` returns one `sqlglot.exp.Block` for a submitted script and retains the statements in order. `classify_script` returns one kind for that block. `SET` statements stay in the block as configuration. A script containing only settings is `OTHER`, a script with multiple different operation kinds is `MIXED`, and any unrecognized statement makes the script `UNKNOWN`.
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from sqlglot_odps import classify_script, parse_script
|
|
54
|
+
|
|
55
|
+
sql = """
|
|
56
|
+
SET odps.sql.type.system.odps2=true;
|
|
57
|
+
SET odps.sql.submit.mode=script;
|
|
58
|
+
SELECT 1 AS id;
|
|
59
|
+
"""
|
|
60
|
+
script = parse_script(sql)
|
|
61
|
+
print(classify_script(sql).value) # DQL
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
`classify` returns one `StatementKind` per parsed statement, in script order. For an existing SQLGlot statement or block, call `statement_kind(ast)`.
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from sqlglot import parse_one
|
|
68
|
+
from sqlglot_odps import classify, statement_kind
|
|
69
|
+
|
|
70
|
+
sql = """
|
|
71
|
+
SET odps.sql.type.system.odps2=true;
|
|
72
|
+
CREATE TABLE staging LIFECYCLE 7 AS SELECT id FROM events;
|
|
73
|
+
WITH src AS (SELECT id FROM staging) INSERT INTO target SELECT id FROM src;
|
|
74
|
+
SELECT id FROM target;
|
|
75
|
+
"""
|
|
76
|
+
print([kind.value for kind in classify(sql)]) # ['OTHER', 'DDL', 'DML', 'DQL']
|
|
77
|
+
|
|
78
|
+
ast = parse_one("SHOW PARTITIONS target", read="odps")
|
|
79
|
+
print(statement_kind(ast).value) # DQL
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
| Kind | Examples |
|
|
83
|
+
|---|---|
|
|
84
|
+
| `DDL` | `CREATE` including CTAS, `ALTER`, `DROP`, `TRUNCATE TABLE` |
|
|
85
|
+
| `DML` | `INSERT`, `UPDATE`, `DELETE`, `MERGE`, data loading and transfer |
|
|
86
|
+
| `DQL` | Queries and set operations, supported `SHOW` variants, `DESCRIBE`, `EXPLAIN`, `READ` |
|
|
87
|
+
| `OTHER` | `SET`, `USE`, parsed `GRANT` and `REVOKE`, `ANALYZE`, native SQL variable assignments |
|
|
88
|
+
| `MIXED` | A script with multiple different operation kinds |
|
|
89
|
+
| `UNKNOWN` | Opaque or unrecognized statements, and empty scripts |
|
|
90
|
+
|
|
91
|
+
Empty statements and comments are skipped. SQLGlot parse and tokenizer errors propagate to the caller. Classification describes the outer operation. A query inside CTAS or `INSERT` supplies rows to that operation. An `EXPLAIN` that contains an `INSERT` is a DQL operation.
|
|
92
|
+
|
|
93
|
+
### Statement syntax
|
|
94
|
+
|
|
95
|
+
This checkout adds structured parsing and MaxCompute SQL generation for shared-source multi-insert, partition-targeted writes, `INSERT OVERWRITE ... IF NOT EXISTS`, auto partitioning and clustering, multi-partition alter, column-level truncate, temporary CTAS, Java function resources, and selected metadata and data-loading statements. Queries preserve `QUALIFY`, time travel, `ZORDER BY`, named struct fields, and `@` variables when rendered as MaxCompute SQL.
|
|
96
|
+
|
|
97
|
+
Coverage is partial. Compound `BEGIN ... END` scripts require a script parser, and less common administrative commands may produce `UNKNOWN` or a parse error. Compatibility tests exercise SQL syntax. Server-side feature flags, name resolution, and execution require MaxCompute. For MaxCompute-specific statement extensions, generate with `write="odps"`; migration to another engine requires checking the semantics of each clause.
|
|
98
|
+
|
|
99
|
+
## What's supported
|
|
100
|
+
|
|
101
|
+
### Parser — MaxCompute → canonical AST
|
|
102
|
+
|
|
103
|
+
| Category | Functions |
|
|
104
|
+
|---|---|
|
|
105
|
+
| Date arithmetic | `DATEADD`, `DATE_SUB`, `DATEDIFF`, `ADD_MONTHS`, `MONTHS_BETWEEN` |
|
|
106
|
+
| Date extraction | `DATEPART`, `DATETRUNC`, `TRUNC_TIME`, `DAY`, `MONTH`, `YEAR`, `HOUR`, `MINUTE`, `SECOND`, `QUARTER`, `DAYOFMONTH`, `DAYOFWEEK`, `DAYOFYEAR`, `WEEKDAY`, `WEEKOFYEAR` |
|
|
107
|
+
| Date conversion | `TO_DATE`, `DATE_FORMAT`, `TO_CHAR`, `FROM_UNIXTIME`, `FROM_UTC_TIMESTAMP`, `TO_MILLIS`, `ISDATE` |
|
|
108
|
+
| Current date/time | `GETDATE`, `NOW`, `CURRENT_TIMESTAMP`, `CURRENT_TIMEZONE` |
|
|
109
|
+
| Last/next day | `LAST_DAY`, `LASTDAY`, `NEXT_DAY` |
|
|
110
|
+
| String | `TOLOWER`, `TOUPPER`, `REGEXP_COUNT`, `SPLIT_PART`, `SUBSTR` |
|
|
111
|
+
| Aggregate | `WM_CONCAT`, `COUNT_IF`, `ARG_MAX`, `ARG_MIN`, `MAX_BY`, `MIN_BY`, `ANY_VALUE`, `APPROX_DISTINCT`, `STDDEV_SAMP`, `COVAR_POP`, `COVAR_SAMP`, `CORR`, `MEDIAN`, `PERCENTILE_APPROX`, `BITWISE_AND_AGG`, `BITWISE_OR_AGG`, `BITWISE_XOR_AGG` |
|
|
112
|
+
| Array | `ALL_MATCH`, `ANY_MATCH`, `ARRAY_SORT`, `ARRAY_DISTINCT`, `ARRAY_EXCEPT`, `ARRAY_JOIN`, `ARRAY_MAX`, `ARRAY_MIN`, `ARRAYS_OVERLAP`, `ARRAYS_ZIP`, `ARRAY_INTERSECT`, `ARRAY_POSITION`, `ARRAY_REMOVE`, `ARRAY_CONTAINS`, `SLICE` |
|
|
113
|
+
| Map | `MAP_CONCAT`, `MAP_FROM_ENTRIES` |
|
|
114
|
+
| JSON / misc | `FROM_JSON`, `GET_JSON_OBJECT`, `JSON_TUPLE`, `GET_USER_ID`, `REGEXP_SUBSTR`, `TO_MILLIS`, `ISDATE` |
|
|
115
|
+
|
|
116
|
+
Functions not listed are handled via Hive inheritance and work without explicit mapping (e.g. `SPLIT`, `REGEXP_EXTRACT`, `COLLECT_LIST`, `PERCENTILE`, all math/trig functions, window functions).
|
|
117
|
+
|
|
118
|
+
### Generator — canonical AST → MaxCompute SQL
|
|
119
|
+
|
|
120
|
+
Explicit transforms on top of Hive:
|
|
121
|
+
|
|
122
|
+
| Expression | MaxCompute output | Note |
|
|
123
|
+
|---|---|---|
|
|
124
|
+
| `DATEADD` / `DATE_SUB` | `DATEADD(dt, ±n, 'UNIT')` | Correct negation for `DATE_SUB` |
|
|
125
|
+
| `DATEDIFF` | `DATEDIFF(dt1, dt2[, unit])` | |
|
|
126
|
+
| `DATETRUNC` | `DATETRUNC(dt, 'unit')` | Week units: `'week(monday)'` etc. |
|
|
127
|
+
| `DATEPART` | `DATEPART(dt, 'UNIT')` | |
|
|
128
|
+
| `TO_DATE(str, fmt)` | `TO_DATE(str, fmt)` | Maps to `exp.StrToTime` (DATETIME) |
|
|
129
|
+
| `TO_DATE(str)` | `TO_DATE(str)` | Maps to `exp.TsOrDsToDate` (DATE) |
|
|
130
|
+
| `CurrentTimestamp` | `GETDATE()` | Covers `GETDATE`, `NOW`, `CURRENT_TIMESTAMP` |
|
|
131
|
+
| `CurrentDatetime` | `NOW()` | For BigQuery-origin `CURRENT_DATETIME` |
|
|
132
|
+
| `SPACE(n)` | `SPACE(n)` | Hive emits `REPEAT(' ', n)` |
|
|
133
|
+
| `VAR_POP(x)` | `VAR_POP(x)` | Hive emits `VARIANCE_POP` |
|
|
134
|
+
| `VAR_SAMP(x)` | `VAR_SAMP(x)` | Hive emits `VARIANCE` |
|
|
135
|
+
| `INSTR(str, sub)` | `INSTR(str, sub)` | Hive emits `LOCATE(sub, str)` |
|
|
136
|
+
| `SUBSTR(str, pos, len)` | `SUBSTR(...)` | Hive emits `SUBSTRING` |
|
|
137
|
+
| Type: `VARCHAR`/`CHAR`/`TEXT` | `STRING` | |
|
|
138
|
+
| Type: `DATETIME` | `DATETIME` | |
|
|
139
|
+
|
|
140
|
+
### DDL
|
|
141
|
+
|
|
142
|
+
- `LIFECYCLE n` — table retention in days
|
|
143
|
+
- `RANGE CLUSTERED BY (cols) [SORTED BY (cols)] INTO n BUCKETS`
|
|
144
|
+
- `AUTO PARTITIONED BY (TRUNC_TIME(col, 'unit') [AS alias])`
|
|
145
|
+
- `TBLPROPERTIES ('key'='value')` — coexists correctly with `LIFECYCLE`
|
|
146
|
+
- `COMMENT` on columns and tables
|
|
147
|
+
|
|
148
|
+
## Development
|
|
149
|
+
|
|
150
|
+
```bash
|
|
151
|
+
uv sync # install dependencies
|
|
152
|
+
uv run pytest # run all tests
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
## License
|
|
156
|
+
|
|
157
|
+
MIT
|
|
158
|
+
|
|
159
|
+
## License
|
|
160
|
+
|
|
161
|
+
MIT. This project builds on [azurechen97/sqlglot-maxcompute 0.4.0](https://github.com/azurechen97/sqlglot-maxcompute/tree/v0.4.0) and retains the original copyright notice. See [LICENSE](LICENSE).
|
|
162
|
+
|
|
163
|
+
## Contributing
|
|
164
|
+
|
|
165
|
+
Use Python 3.9 or newer. Run the regression suite with `uv run --locked pytest`. Use `python -m build` to build a wheel and source distribution.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "sqlglot-odps"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "MaxCompute dialect plugin for SQLGlot"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
authors = [
|
|
9
|
+
{ name = "azurechen97" }
|
|
10
|
+
]
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
dependencies = [
|
|
13
|
+
"sqlglot>=30.1.0,<31",
|
|
14
|
+
]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 3 - Alpha",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Intended Audience :: Science/Research",
|
|
19
|
+
"Operating System :: OS Independent",
|
|
20
|
+
"Programming Language :: SQL",
|
|
21
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
maintainers = [{ name = "Dingxin" }]
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://github.com/dingxin-tech/sqlglot-odps"
|
|
28
|
+
Repository = "https://github.com/dingxin-tech/sqlglot-odps"
|
|
29
|
+
|
|
30
|
+
[build-system]
|
|
31
|
+
requires = ["hatchling"]
|
|
32
|
+
build-backend = "hatchling.build"
|
|
33
|
+
|
|
34
|
+
[dependency-groups]
|
|
35
|
+
dev = [
|
|
36
|
+
"pytest>=7.0",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
[tool.pytest.ini_options]
|
|
40
|
+
testpaths = ["tests"]
|
|
41
|
+
|
|
42
|
+
[project.entry-points."sqlglot.dialects"]
|
|
43
|
+
odps = "sqlglot_odps.dialect:Odps"
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from sqlglot_odps.dialect import Odps
|
|
2
|
+
from sqlglot_odps.generator import OdpsGenerator
|
|
3
|
+
from sqlglot_odps.parser import OdpsParser
|
|
4
|
+
from sqlglot_odps.statements import (
|
|
5
|
+
StatementKind,
|
|
6
|
+
classify,
|
|
7
|
+
classify_script,
|
|
8
|
+
parse_script,
|
|
9
|
+
statement_kind,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"Odps",
|
|
14
|
+
"OdpsParser",
|
|
15
|
+
"OdpsGenerator",
|
|
16
|
+
"StatementKind",
|
|
17
|
+
"classify",
|
|
18
|
+
"classify_script",
|
|
19
|
+
"parse_script",
|
|
20
|
+
"statement_kind",
|
|
21
|
+
]
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from sqlglot.dialects.hive import Hive
|
|
4
|
+
from sqlglot.tokens import TokenType
|
|
5
|
+
|
|
6
|
+
from sqlglot_odps.generator import OdpsGenerator
|
|
7
|
+
from sqlglot_odps.parser import OdpsParser
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Odps(Hive):
|
|
11
|
+
ALIAS_POST_VERSION = False
|
|
12
|
+
|
|
13
|
+
TIME_MAPPING = {
|
|
14
|
+
"yyyy": "%Y",
|
|
15
|
+
"yy": "%y",
|
|
16
|
+
"mm": "%m",
|
|
17
|
+
"dd": "%d",
|
|
18
|
+
"hh": "%H",
|
|
19
|
+
"mi": "%M",
|
|
20
|
+
"ss": "%S",
|
|
21
|
+
"ff3": "%f",
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
DATE_FORMAT = "'yyyy-mm-dd'"
|
|
25
|
+
TIME_FORMAT = "'yyyy-mm-dd hh:mi:ss'"
|
|
26
|
+
|
|
27
|
+
class Tokenizer(Hive.Tokenizer):
|
|
28
|
+
COMMANDS = Hive.Tokenizer.COMMANDS - {TokenType.SHOW}
|
|
29
|
+
KEYWORDS = {
|
|
30
|
+
**Hive.Tokenizer.KEYWORDS,
|
|
31
|
+
"EXPLAIN": TokenType.DESCRIBE,
|
|
32
|
+
"LIFECYCLE": TokenType.KEY,
|
|
33
|
+
"OPTION": TokenType.OPTION,
|
|
34
|
+
"ZORDER BY": TokenType.SORT_BY,
|
|
35
|
+
"TIMESTAMP AS OF": TokenType.FOR,
|
|
36
|
+
"TIMESTAMP BETWEEN": TokenType.FOR,
|
|
37
|
+
"VERSION AS OF": TokenType.FOR,
|
|
38
|
+
"VERSION BETWEEN": TokenType.FOR,
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
Parser = OdpsParser
|
|
42
|
+
Generator = OdpsGenerator
|