sqlglot-odps 0.1.0__py3-none-any.whl

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/py.typed ADDED
File without changes
@@ -0,0 +1,86 @@
1
+ from __future__ import annotations
2
+
3
+ from enum import Enum
4
+
5
+ from sqlglot import exp, parse
6
+
7
+ from sqlglot_odps.dialect import Odps
8
+
9
+
10
+ class StatementKind(str, Enum):
11
+ DDL = "DDL"
12
+ DML = "DML"
13
+ DQL = "DQL"
14
+ MIXED = "MIXED"
15
+ OTHER = "OTHER"
16
+ UNKNOWN = "UNKNOWN"
17
+
18
+
19
+ def statement_kind(statement: exp.Expr) -> StatementKind:
20
+ """Classify an already parsed MaxCompute statement or script block."""
21
+ if isinstance(statement, exp.Block):
22
+ return _block_kind(statement)
23
+ while isinstance(statement, exp.Subquery) and statement.is_wrapper:
24
+ statement = statement.this
25
+
26
+ # SQLGlot's Insert implements both DML and DDL. Its query supplies rows to write.
27
+ if isinstance(
28
+ statement, (exp.DML, exp.MultitableInserts, exp.LoadData, exp.Export)
29
+ ):
30
+ return StatementKind.DML
31
+ if isinstance(statement, (exp.Create, exp.Alter, exp.Drop, exp.TruncateTable)):
32
+ return StatementKind.DDL
33
+ if isinstance(statement, (exp.Select, exp.SetOperation, exp.Describe, exp.Show)):
34
+ return StatementKind.DQL
35
+ if isinstance(statement, (exp.Set, exp.Use, exp.Grant, exp.Revoke, exp.Analyze)):
36
+ return StatementKind.OTHER
37
+ if isinstance(statement, exp.PropertyEQ) and isinstance(
38
+ statement.this, exp.Parameter
39
+ ):
40
+ return StatementKind.OTHER
41
+ return StatementKind.UNKNOWN
42
+
43
+
44
+ def _block_kind(block: exp.Block) -> StatementKind:
45
+ statements = [
46
+ statement
47
+ for statement in block.expressions
48
+ if statement is not None and not isinstance(statement, exp.Semicolon)
49
+ ]
50
+ kinds = {
51
+ statement_kind(statement)
52
+ for statement in statements
53
+ if not isinstance(statement, exp.Set)
54
+ }
55
+ if not kinds:
56
+ return StatementKind.OTHER if statements else StatementKind.UNKNOWN
57
+ if StatementKind.UNKNOWN in kinds:
58
+ return StatementKind.UNKNOWN
59
+ if len(kinds) > 1:
60
+ return StatementKind.MIXED
61
+ return kinds.pop()
62
+
63
+
64
+ def parse_script(sql: str) -> exp.Block:
65
+ """Parse one submitted SQL script and keep its statements in order."""
66
+ return exp.Block(
67
+ expressions=[
68
+ statement
69
+ for statement in parse(sql, read=Odps)
70
+ if statement is not None and not isinstance(statement, exp.Semicolon)
71
+ ]
72
+ )
73
+
74
+
75
+ def classify_script(sql: str) -> StatementKind:
76
+ """Classify a submitted script as a unit, excluding SET from its operation kinds."""
77
+ return statement_kind(parse_script(sql))
78
+
79
+
80
+ def classify(sql: str) -> list[StatementKind]:
81
+ """Classify each statement in order, skipping empty statements and comments.
82
+
83
+ SQLGlot parse/token errors propagate. A successfully parsed opaque command
84
+ or expression outside the supported statement families is UNKNOWN.
85
+ """
86
+ return [statement_kind(statement) for statement in parse_script(sql).expressions]
@@ -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,11 @@
1
+ sqlglot_odps/__init__.py,sha256=BYg8oqyZxbHQUxEr4fE8q_mRk6tEXvJjXn3Z5eppLf4,430
2
+ sqlglot_odps/dialect.py,sha256=we6MD0FtrOhoIu2Z597jTuIqh_VYK0a4Ls1sqcEC_KU,1099
3
+ sqlglot_odps/generator.py,sha256=em4jBFs-8MBszpKF01kR0KUnKFDkO2jz3PKde6ip8OY,16453
4
+ sqlglot_odps/parser.py,sha256=cbZokmdQC6eufX8nAc34-NPL7eCWwK2L0ClTdHdDiv8,30578
5
+ sqlglot_odps/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ sqlglot_odps/statements.py,sha256=3K0NVf-O30SPybRA_u-ZAd1w0yDnVX35XqQCxf4Y6U0,2848
7
+ sqlglot_odps-0.1.0.dist-info/METADATA,sha256=AuLZu12U1h_6I2U5qHG_bk260BoM0i1GCTaeulqOLe8,8566
8
+ sqlglot_odps-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ sqlglot_odps-0.1.0.dist-info/entry_points.txt,sha256=VJaJ3a8mKaQf51Cx4LLsjNeBOORlGrCGzRiTBfFbJgY,52
10
+ sqlglot_odps-0.1.0.dist-info/licenses/LICENSE,sha256=fGkxiqE6h9s0uZyFq6sLrVPKZEErBa_BIYicE0HRZCQ,1067
11
+ sqlglot_odps-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [sqlglot.dialects]
2
+ odps = sqlglot_odps.dialect:Odps
@@ -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.